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

// Database connection
include 'connect.php';

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

// Calculate current week's start and end dates
$startOfWeek = date('Y-m-d', strtotime('monday this week'));
$endOfWeek = date('Y-m-d', strtotime('sunday this week'));

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Fetch data from form
   // $start_date = mysqli_real_escape_string($conn, $_POST['start_date']);
    //$end_date = mysqli_real_escape_string($conn, $_POST['end_date']);

    $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;



    // Validate date input
    if (!empty($start_date) && !empty($end_date)) {
        // Fetch sales data between the date range
        $query = "SELECT * FROM purchase_table WHERE purchase_time BETWEEN '$start_date' AND '$end_date'";
        $result = mysqli_query($conn, $query);

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

// Handle credit payment
if (isset($_POST['pay_debt'])) {
    $purchase_id = intval($_POST['purchase_id']);
    $payment_amount = floatval($_POST['payment_amount']);
    
    // Fetch the sale details
    $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) {
            // Update paid amount
            $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 debt is fully paid, you could update a status or alert the user
            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 sale!';
    }
}

// Close the database connection
mysqli_close($conn);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Fetch Sales Data</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
</head>
<body>
    <h1>Purchases Overview</h1>

    <!-- Display message after payment -->
    <?php if ($message): ?>
        <p><?php echo $message; ?></p>
    <?php endif; ?>

    <!-- Date range form to fetch sales data -->
    <form method="POST" action="">
        <label for="start_date">Start Date:</label>
        <input type="date" id="start_date" name="start_date" value="<?php echo $startOfWeek; ?>" required>
        
        <label for="end_date">End Date:</label>
        <input type="date" id="end_date" name="end_date" value="<?php echo $endOfWeek; ?>" required>
        
        <button type="submit">Fetch Data</button>
    </form>

    <!-- Display sales data if results exist -->
    <?php if (!empty($results)): ?>
        <div class="container my-5">
            <table border="1" class="table table-hover">
                <thead>
                    <tr>
                        <th>DATE</th>
                        <th>SUPLIER</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>
                                <?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">
                                        <input type="hidden" name="purchase_id" value="<?php echo $row['purchase_id']; ?>">
                                        <input type="number" name="payment_amount" min="0.01" step="0.01" required>
                                        <button type="submit" name="pay_debt">Pay Debt</button>
                                    </form>
                                <?php } else { ?>
                                    Paid/No debt
                                <?php } ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php elseif ($_SERVER['REQUEST_METHOD'] == 'POST'): ?>
        <p>No data found for the selected date range.</p>
    <?php endif; ?>
</body>
</html>
