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

include 'connect.php';

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

// Get the current date (today)
$currentDate = date('Y-m-d');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $start_date = isset($_POST['start_date']) ? mysqli_real_escape_string($conn, $_POST['start_date']) : null;
    $end_date = isset($_POST['end_date']) ? mysqli_real_escape_string($conn, $_POST['end_date']) : null;

    // If no dates are provided, default to today's date
    if (empty($start_date)) {
        $start_date = $currentDate;
    }
    if (empty($end_date)) {
        $end_date = $currentDate;
    }

    // Modify the query to fetch records within the full day of the selected date
    $start_datetime = $start_date . ' 00:00:00';  // Start of the selected date
    $end_datetime = $end_date . ' 23:59:59';      // End of the selected date

    // Fetch data based on the provided date range
    if (!empty($start_date) && !empty($end_date)) {
        $query = "SELECT * FROM purchase_table WHERE purchase_time BETWEEN '$start_datetime' AND '$end_datetime'";
        $result = mysqli_query($conn, $query);

        if ($result) {
            $results = mysqli_fetch_all($result, MYSQLI_ASSOC);
        } else {
            $message = "Error: " . mysqli_error($conn);
        }
    } else {
        $message = "Please select both start and end date.";
    }
}

// Handling credit debt payments
if (isset($_POST['pay_debt'])) {
    $purchase_id = intval($_POST['purchase_id']);
    $payment_amount = floatval($_POST['payment_amount']);
    
    $query = "SELECT * FROM purchase_table WHERE purchase_id = '$purchase_id'";
    $result = mysqli_query($conn, $query);
    $purchase = mysqli_fetch_assoc($result);

    if ($purchase['payment_method'] == 'Credit') {
        $remaining_debt = $purchase['total_amount'] - $purchase['paid_amount'];

        if ($payment_amount <= $remaining_debt) {
            $new_paid_amount = $purchase['paid_amount'] + $payment_amount;
            $update_query = "UPDATE purchase_table SET paid_amount = '$new_paid_amount' WHERE purchase_id = '$purchase_id'";
            mysqli_query($conn, $update_query);
            
            $message = 'Payment successful!';

            if ($new_paid_amount >= $purchase['total_amount']) {
                $message .= " Debt fully paid!";
            }
        } else {
            $message = 'Payment exceeds the remaining debt!';
        }
    } else {
        $message = 'Cannot make a payment for cash purchase!';
    }
}

mysqli_close($conn);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Purchases 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">Purchases Overview(Cash & Credit)</h1>
    </div>

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

    <!-- Date range filter form -->
    <form method="POST" action="" 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 $currentDate; ?>" 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 $currentDate; ?>" 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>

    <!-- Display purchase data if available -->
    <?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>SUPPLIER</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['purchase_time']); ?></td>
                            <td><?php echo htmlspecialchars($row['sup_name']); ?></td>
                            <td><?php echo htmlspecialchars($row['product_number']); ?></td>
                            <td><?php echo htmlspecialchars($row['pr_Name']); ?></td>
                            <td><?php echo htmlspecialchars($row['quantity_purchased']); ?></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 action="" method="POST" class="d-flex">
                                        <input type="hidden" name="purchase_id" value="<?php echo $row['purchase_id']; ?>">
                                        <input type="number" name="payment_amount" class="form-control form-control-sm me-2" min="0.01" step="0.01" 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>
