<?php
include("../classes/manager.class.php");

$m = new Manager();

if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}

global $db;

$adjustment_date = isset($_POST['adjustment_date']) ? $_POST['adjustment_date'] : '';
$reason          = isset($_POST['reason']) ? trim($_POST['reason']) : '';
$ingredient_id   = isset($_POST['ingredient_id']) ? (int)$_POST['ingredient_id'] : 0;
$purchase_id     = isset($_POST['purchase_id']) ? (int)$_POST['purchase_id'] : 0;
$deduct_qty      = isset($_POST['deduct_qty']) ? (float)$_POST['deduct_qty'] : 0;

if ($ingredient_id <= 0 || $purchase_id <= 0 || $deduct_qty <= 0 || $reason == '' || $adjustment_date == '') {
    echo "<script>alert('Please fill all required fields.'); window.history.back();</script>";
    exit();
}

// Convert dd-mm-yyyy -> Y-m-d
$adj_date_db = date('Y-m-d', strtotime($adjustment_date));
$now = date('Y-m-d H:i:s');
$user_id = (int)$_SESSION['sess_userid'];

$db->query("START TRANSACTION");

try {

    // Lock lots FIFO by batch_date
    $lotsQ = "
        SELECT id, remaining_qty, reserved_qty, batch_date
        FROM ingredient_stock
        WHERE ingredient_id = '$ingredient_id'
          AND purchase_id   = '$purchase_id'
        ORDER BY batch_date ASC, id ASC
        FOR UPDATE
    ";
    $lots = $db->fetch_all_array($lotsQ);

    if (!$lots) {
        $db->query("ROLLBACK");
        echo "<script>alert('No stock lots found for selected ingredient/purchase.'); window.history.back();</script>";
        exit();
    }

    $before_rem = 0.0;
    $before_used = 0.0;
    foreach ($lots as $l) {
        $before_rem  += (float)$l->remaining_qty;
        $before_used += (float)$l->reserved_qty;
    }

    if ($deduct_qty > $before_rem) {
        $db->query("ROLLBACK");
        echo "<script>alert('Deduct qty cannot exceed remaining qty. Remaining: " . number_format($before_rem, 6) . "'); window.history.back();</script>";
        exit();
    }

    // Deduct from remaining, add into reserved (your meaning)
    $left = $deduct_qty;

    foreach ($lots as $lot) {
        if ($left <= 0) break;

        $id  = (int)$lot->id;
        $rem = (float)$lot->remaining_qty;
        $used = (float)$lot->reserved_qty;

        if ($rem <= 0) continue;

        $take = min($rem, $left);

        $new_rem = $rem - $take;
        $new_used = $used + $take;

        $status = ($new_rem <= 0) ? 'Used' : 'Available';

        // Keep available_qty synced (your reports use it) :contentReference[oaicite:4]{index=4}
        $updateData = [
            'reserved_qty'  => $new_used,
            'remaining_qty' => $new_rem,
            'available_qty' => $new_rem,
            'status'        => $status,
            'last_updated'  => $now
        ];

        $db->query_update(TABLE_INGREDIENT_STOCK, $updateData, "id='$id'");

        $left -= $take;
    }

    if ($left > 0) {
        $db->query("ROLLBACK");
        echo "<script>alert('Unable to deduct full quantity.'); window.history.back();</script>";
        exit();
    }

    // After totals
    $afterQ = "
        SELECT
            COALESCE(SUM(reserved_qty),0) AS used_qty,
            COALESCE(SUM(remaining_qty),0) AS remaining_qty
        FROM ingredient_stock
        WHERE ingredient_id = '$ingredient_id'
          AND purchase_id   = '$purchase_id'
    ";
    $after = $db->query_first($afterQ);

    $after_used = isset($after->used_qty) ? (float)$after->used_qty : 0.0;
    $after_rem  = isset($after->remaining_qty) ? (float)$after->remaining_qty : 0.0;

    // Insert log row (assumes these columns exist in your table)
    $log = [
        'code' => 'TEMP',
        'adjustment_date' => $adj_date_db,
        'ingredient_id' => $ingredient_id,
        'purchase_id' => $purchase_id,
        'deduct_qty' => $deduct_qty,
        'before_used_qty' => $before_used,
        'after_used_qty' => $after_used,
        'before_remaining_qty' => $before_rem,
        'after_remaining_qty' => $after_rem,
        'reason' => addslashes($reason),
        'created_by' => $user_id,
        'create_date' => $now,
        'datetime' => $now,
        'status' => 'Posted'
    ];

    $adj_id = $db->query_insert('ingredient_stock_adjustment', $log);

    if (!$adj_id || $db->affected_rows <= 0) {
        $db->query("ROLLBACK");
        echo "<script>alert('Failed to save adjustment log. SQL Error: " . addslashes($db->last_error) . "'); window.history.back();</script>";
        exit();
    }

    // Generate ISA-000001
    $code = 'ISA-' . str_pad((int)$adj_id, 6, '0', STR_PAD_LEFT);
    $db->query("UPDATE ingredient_stock_adjustment SET code='$code' WHERE id='" . (int)$adj_id . "'");

    $db->query("COMMIT");

    echo "<script>alert('Stock adjustment posted successfully. Code: $code'); window.location.href='ingredient_stock_adjustment_setup.php';</script>";
    exit();

} catch (Exception $e) {
    $db->query("ROLLBACK");
    echo "<script>alert('Error: " . addslashes($e->getMessage()) . "'); window.history.back();</script>";
    exit();
}
