<?php
session_start();
if (!isset($_SESSION['username'])) {
    echo "<script>window.top.location.href='index.php';</script>";
    exit();
}

include 'connect.php';

$results = [];
$message = '';

$startOfWeek = date('Y-m-d', strtotime('monday this week'));
$endOfWeek = date('Y-m-d', strtotime('sunday this week'));

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['start_date'], $_POST['end_date'])) {
        $start_date = $_POST['start_date'];
        $end_date = $_POST['end_date'];

        $stmt = $conn->prepare("SELECT sell_id, sell_time, cust_name, product_number, pr_Name, quantity_sold, total_amount, payment_method, paid_amount FROM sell WHERE sell_time BETWEEN ? AND ?");
        $stmt->bind_param("ss", $start_date, $end_date);
        $stmt->execute();
        $result = $stmt->get_result();
        $results = $result->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
    } elseif (isset($_POST['pay_debt'])) {
        $sale_id = intval($_POST['sale_id']);
        $payment_amount = floatval($_POST['payment_amount']);

        $stmt = $conn->prepare("SELECT total_amount, paid_amount, payment_method FROM sell WHERE sell_id = ?");
        $stmt->bind_param("i", $sale_id);
        $stmt->execute();
        $sale = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if ($sale && $sale['payment_method'] == 'Credit') {
            $remaining_debt = $sale['total_amount'] - $sale['paid_amount'];
            if ($payment_amount > 0 && $payment_amount <= $remaining_debt) {
                $new_paid_amount = $sale['paid_amount'] + $payment_amount;
                $stmt = $conn->prepare("UPDATE sell SET paid_amount = ? WHERE sell_id = ?");
                $stmt->bind_param("di", $new_paid_amount, $sale_id);
                $stmt->execute();
                $stmt->close();
                $message = 'Payment successful!';
                if ($new_paid_amount >= $sale['total_amount']) {
                    $message .= " Debt fully paid!";
                }
            } else {
                $message = 'Invalid payment amount!';
            }
        } else {
            $message = 'Cannot make a payment for cash sale!';
        }
    }
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Sales Overview</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
</head>
<body class="container py-4">
    <div class="text-center mb-4">
        <h1 class="display-6">Sales Overview</h1>
    </div>

    <?php if ($message): ?>
        <div class="alert alert-info"> <?php echo $message; ?> </div>
    <?php endif; ?>

    <form method="POST" class="bg-light p-4 rounded shadow-sm">
        <div class="row g-3">
            <div class="col-md-5">
                <label for="start_date" class="form-label">Start Date:</label>
                <input type="date" id="start_date" name="start_date" class="form-control" value="<?php echo $startOfWeek; ?>" required>
            </div>
            <div class="col-md-5">
                <label for="end_date" class="form-label">End Date:</label>
                <input type="date" id="end_date" name="end_date" class="form-control" value="<?php echo $endOfWeek; ?>" required>
            </div>
            <div class="col-md-2 align-self-end">
                <button type="submit" class="btn btn-primary w-100">Fetch Data</button>
            </div>
        </div>
    </form>

    <?php if (!empty($results)): ?>
        <div class="table-responsive mt-4">
            <table class="table table-bordered table-hover">
                <thead class="table-dark text-center">
                    <tr>
                        <th>DATE</th>
                        <th>SELL ID</th>
                        <th>CUSTOMER</th>
                        <th>CODE</th>
                        <th>PR.NAME</th>
                        <th>QTY</th>
                        <th>TOTAL</th>
                        <th>P.METHOD</th>
                        <th>P.AMOUNT</th>
                        <th>OUT/BAL</th>
                        <th>DEBT</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($results as $row): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($row['sell_time']); ?></td>
                            <td><?php echo htmlspecialchars($row['sell_id']); ?></td>
                            <td><?php echo htmlspecialchars($row['cust_name']); ?></td>
                            <td><?php echo htmlspecialchars($row['product_number']); ?></td>
                            <td><?php echo htmlspecialchars($row['pr_Name']); ?></td>
                            <td><?php echo htmlspecialchars($row['quantity_sold']); ?></td>
                            <td><?php echo number_format($row['total_amount'], 2); ?></td>
                            <td><?php echo htmlspecialchars($row['payment_method']); ?></td>
                            <td><?php echo number_format($row['paid_amount'], 2); ?></td>
                            <td class="text-danger fw-bold">
                                <?php
                                if ($row['payment_method'] == 'Credit') {
                                    $remaining_debt = $row['total_amount'] - $row['paid_amount'];
                                    echo number_format($remaining_debt, 2);
                                } else {
                                    echo 'N/A';
                                }
                                ?>
                            </td>
                            <td>
                                <?php if ($row['payment_method'] == 'Credit' && $row['total_amount'] > $row['paid_amount']) { ?>
                                    <form method="POST" class="d-flex">
                                        <input type="hidden" name="sale_id" value="<?php echo $row['sell_id']; ?>">
                                        <input type="number" name="payment_amount" class="form-control form-control-sm me-2" min="0.01" step="0.01" max="<?php echo $remaining_debt; ?>" required>
                                        <button type="submit" name="pay_debt" class="btn btn-success btn-sm">Pay Debt</button>
                                    </form>
                                <?php } else { ?>
                                    <span class="badge bg-success">Paid/No debt</span>
                                <?php } ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php elseif ($_SERVER['REQUEST_METHOD'] == 'POST'): ?>
        <div class="alert alert-warning mt-4">No data found for the selected date range.</div>
    <?php endif; ?>
</body>
</html>
