<?php
// Include the database connection
include 'includes/config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate input
    $cheque_id = isset($_POST['cheque_id']) ? intval($_POST['cheque_id']) : 0;
    $hold_until = isset($_POST['hold_until']) ? $_POST['hold_until'] : '';

    if ($cheque_id > 0 && !empty($hold_until)) {
        try {
            // Update the hold_until date and status in the database
            $sql = "UPDATE `cheque_payments` 
                    SET `hold_until` = :hold_until, `status` = 'hold' 
                    WHERE `id` = :cheque_id";
            $stmt = $conn->prepare($sql);
            $stmt->bindParam(':hold_until', $hold_until);
            $stmt->bindParam(':cheque_id', $cheque_id);

            if ($stmt->execute()) {
                // Show an alert and redirect using JavaScript
                echo "<script>
                    alert('Hold Until date and status updated successfully!');
                    window.location.href = 'list_cheque.php';
                </script>";
                exit;
            } else {
                // Show an error alert and redirect
                echo "<script>
                    alert('Failed to update Hold Until date and status.');
                    window.location.href = 'list_cheque.php';
                </script>";
                exit;
            }
        } catch (PDOException $e) {
            // Handle database errors
            error_log("Database Error: " . $e->getMessage());
            echo "<script>
                alert('A database error occurred.');
                window.location.href = 'list_cheque.php';
            </script>";
            exit;
        }
    } else {
        // Show an error alert for invalid input
        echo "<script>
            alert('Invalid input data.');
            window.location.href = 'list_cheque.php';
        </script>";
        exit;
    }
} else {
    // Redirect if the request method is not POST
    echo "<script>
        alert('Invalid request method.');
        window.location.href = 'list_cheque.php';
    </script>";
    exit;
}
?>
