<?php
session_start();
include "header.php";
include "db.php";

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$user_id = $_SESSION['user_id'];

if (!isset($_GET['sale_id'])) {
    header("Location: dashboard.php");
    exit();
}

$sale_id = intval($_GET['sale_id']);
$error = '';
$success = '';

// Fetch sale record to edit
$stmt = $conn->prepare("SELECT * FROM sales WHERE sale_id = ? AND staff_id = ?");
$stmt->bind_param("ii", $sale_id, $user_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows !== 1) {
    $stmt->close();
    header("Location: dashboard.php");
    exit();
}

$sale = $result->fetch_assoc();
$stmt->close();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $customer_name = !empty($_POST['customer_name']) ? trim($_POST['customer_name']) : null;
    $item_name = trim($_POST['item_name']);
    $description = !empty($_POST['description']) ? trim($_POST['description']) : null;
    $amount_payable = floatval($_POST['amount_payable']);
    $amount_paid = floatval($_POST['amount_paid']);

    if (empty($item_name) || $amount_payable < 0 || $amount_paid < 0) {
        $error = "Please fill in all required fields correctly.";
    } else {
        // Update sale
        $update_stmt = $conn->prepare("UPDATE sales SET customer_name=?, item_name=?, description=?, amount_payable=?, amount_paid=? WHERE sale_id=? AND staff_id=?");
        $update_stmt->bind_param(
            "sssddii",
            $customer_name,
            $item_name,
            $description,
            $amount_payable,
            $amount_paid,
            $sale_id,
            $user_id
        );

        if ($update_stmt->execute()) {
            $success = "Sale updated successfully.";
            // Refresh data for form
            $sale['customer_name'] = $customer_name;
            $sale['item_name'] = $item_name;
            $sale['description'] = $description;
            $sale['amount_payable'] = $amount_payable;
            $sale['amount_paid'] = $amount_paid;
        } else {
            $error = "Error updating sale: " . $conn->error;
        }

        $update_stmt->close();
    }
}
?>

<div class="container mt-4" style="max-width:600px;">
    <h2>Edit Sale</h2>
    <a href="Daily_report.php" class="btn btn-secondary mb-3">Back to Daily Report</a>

    <?php if ($error): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>
    <?php if ($success): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>

    <form method="post" novalidate>
        <div class="mb-3">
            <label for="customer_name" class="form-label">Customer Name (optional)</label>
            <input type="text" class="form-control" id="customer_name" name="customer_name" value="<?= htmlspecialchars($sale['customer_name'] ?? '') ?>">
        </div>

        <div class="mb-3">
            <label for="item_name" class="form-label">Item Name <span class="text-danger">*</span></label>
            <input type="text" class="form-control" id="item_name" name="item_name" required value="<?= htmlspecialchars($sale['item_name']) ?>">
        </div>

        <div class="mb-3">
            <label for="description" class="form-label">Description (optional)</label>
            <textarea class="form-control" id="description" name="description" rows="3"><?= htmlspecialchars($sale['description'] ?? '') ?></textarea>
        </div>

        <div class="mb-3">
            <label for="amount_payable" class="form-label">Amount Payable <span class="text-danger">*</span></label>
            <input type="number" step="0.01" min="0" class="form-control" id="amount_payable" name="amount_payable" required value="<?= htmlspecialchars($sale['amount_payable']) ?>">
        </div>

        <div class="mb-3">
            <label for="amount_paid" class="form-label">Amount Paid <span class="text-danger">*</span></label>
            <input type="number" step="0.01" min="0" class="form-control" id="amount_paid" name="amount_paid" required value="<?= htmlspecialchars($sale['amount_paid']) ?>">
        </div>

        <button type="submit" class="btn btn-primary" onclick="return confirm('Are you sure you want to update this sale?');">Update Sale</button>
    </form>
</div>

<?php include "footer.php"; ?>
