<?php
include 'db.php';
include 'auth_check.php';

$msg = "";

// Get outward ID
if (!isset($_GET['id'])) {
    die("Outward ID is required.");
}

$id = intval($_GET['id']);

// Fetch existing outward entry with its purchase_stock link
$result = $conn->query("
    SELECT o.*, p.qty AS purchased_qty, p.fault_count
    FROM outward_stock o
    LEFT JOIN purchase_stock p ON o.purchase_stock_id = p.id
    WHERE o.id=$id
");
if ($result->num_rows == 0) {
    die("Outward entry not found.");
}

$outward = $result->fetch_assoc();
$purchase_stock_id = intval($outward['purchase_stock_id']);

// Calculate available qty = purchased - total outward - faults + current outward (editing case)
$available_result = $conn->query("
SELECT 
    (ps.qty 
     - COALESCE((SELECT SUM(o2.qty) 
                 FROM outward_stock o2 
                 WHERE o2.purchase_stock_id = ps.id), 0) 
     - COALESCE((SELECT SUM(f.qty) 
                 FROM fault_stock f 
                 WHERE f.purchase_stock_id = ps.id), 0)
    ) AS available_qty
FROM purchase_stock ps
WHERE ps.id = $purchase_stock_id;

");

$available = $available_result->fetch_assoc();
$available_qty = intval($available['available_qty']);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $outward_date = $conn->real_escape_string($_POST['outward_date']);
    $given_to = $conn->real_escape_string(trim($_POST['given_to']));
    $item = $conn->real_escape_string(trim($_POST['item_name']));
    $particular = $conn->real_escape_string(trim($_POST['particular_name']));
    $spec = $conn->real_escape_string(trim($_POST['specification']));
    $model = $conn->real_escape_string(trim($_POST['model_number']));
    $qty = intval($_POST['qty']);
    $remarks = $conn->real_escape_string(trim($_POST['remarks']));

    // Server-side validation
    if ($qty < 0) {
        $msg = "Quantity cannot be negative.";
    } elseif ($qty > $available_qty) {
        $msg = "Quantity exceeds available stock ($available_qty).";
    } else {
        $sql = "UPDATE outward_stock SET
                    outward_date='$outward_date',
                    given_to='$given_to',
                    item_name='$item',
                    particular_name='$particular',
                    specification='$spec',
                    model_number='$model',
                    qty=$qty,
                    remarks='$remarks',
                    purchase_stock_id=$purchase_stock_id
                WHERE id=$id";

        if ($conn->query($sql)) {
            header("Location: outward_view.php");
            exit;
        } else {
            $msg = "Error: " . $conn->error;
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Edit Outward Entry</title>
    <link rel="icon" type="image/png" href="assets/logo/logo_icon.png">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { display: flex; flex-direction: column; min-height: 100vh; }
        .flex-grow-1 { flex: 1; }
        footer { background: #f8f9fa; padding: 10px 0; }
    </style>
</head>
<body class="bg-light">
    <?php
if (session_status() == PHP_SESSION_NONE) session_start();
include 'navbar.php';
?>
<div class="flex-grow-1">
    <div class="container mt-2">
        <h2 class="mb-4 text-center text-success">Edit Outward Entry</h2>
        <?php if($msg != "") { ?>
            <div class="alert alert-danger text-center"><?= htmlspecialchars($msg) ?></div>
        <?php } ?>

        <form method="POST" class="row g-3 shadow p-4 bg-white rounded">
            <div class="col-md-4">
                <label class="form-label">Outward Date</label>
                <input type="date" class="form-control" name="outward_date" value="<?= htmlspecialchars($outward['outward_date']) ?>" required>
            </div>
            <div class="col-md-4">
                <label class="form-label">Given To</label>
                <input type="text" class="form-control" name="given_to" value="<?= htmlspecialchars($outward['given_to']) ?>" required>
            </div>
            <div class="col-md-4">
                <label class="form-label">Item</label>
                <input type="text" class="form-control" name="item_name" value="<?= htmlspecialchars($outward['item_name']) ?>" required>
            </div>
            <div class="col-md-3">
                <label class="form-label">Particular</label>
                <input type="text" class="form-control" name="particular_name" value="<?= htmlspecialchars($outward['particular_name']) ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label">Specification</label>
                <input type="text" class="form-control" name="specification" value="<?= htmlspecialchars($outward['specification']) ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label">Model</label>
                <input type="text" class="form-control" name="model_number" value="<?= htmlspecialchars($outward['model_number']) ?>">
            </div>
            <div class="col-md-2">
                <label class="form-label">Qty</label>
                <input type="number" class="form-control" name="qty" 
                    value="<?= htmlspecialchars($outward['qty']) ?>" 
                    min="0" max="<?= $available_qty ?>" required>
                <small class="text-muted">Available: <?= $available_qty ?></small>
            </div>
            <div class="col-md-12">
                <label class="form-label">Remarks</label>
                <input type="text" class="form-control" name="remarks" value="<?= htmlspecialchars($outward['remarks']) ?>">
            </div>
            <div class="col-12 text-center">
                <button type="submit" class="btn btn-success">Update Outward Entry</button>
                <a href="outward_view.php" class="btn btn-secondary">Back</a>
            </div>
        </form>
    </div>
</div>
    <?php
    if (session_status() == PHP_SESSION_NONE) session_start();
    include 'footer.php';
    ?>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
