<?php
include 'includes/config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $cheque_id = isset($_POST['cheque_id']) ? $_POST['cheque_id'] : '';
    $bank_id = isset($_POST['bank_id']) ? $_POST['bank_id'] : '';
    $customer_id = isset($_POST['customer_id']) ? $_POST['customer_id'] : '';
    $status = isset($_POST['status']) ? $_POST['status'] : ''; 

    try {
        $cleared_date = $status === 'cleared' ? date('Y-m-d H:i:s') : null;

        $updateSql = "UPDATE cheque_payments 
                      SET status = :status, cleared_date = :cleared_date 
                      WHERE id = :cheque_id";
        $stmt = $conn->prepare($updateSql);
        $stmt->bindParam(':status', $status);
        $stmt->bindParam(':cleared_date', $cleared_date);
        $stmt->bindParam(':cheque_id', $cheque_id);
        $stmt->execute();

        $sql = "INSERT INTO cash_deposit (invoice, bank_id, cheque_id, user_id, amount, status, payment_status, date_deposit)
                SELECT invoice_no, :bank_id, id, :customer_id, amount, :status, 'Cheque Cleared', NOW()
                FROM cheque_payments WHERE id = :cheque_id";
        
        $stmt = $conn->prepare($sql);
        $stmt->bindParam(':bank_id', $bank_id);
        $stmt->bindParam(':customer_id', $customer_id);
        $stmt->bindParam(':cheque_id', $cheque_id);
        $stmt->bindParam(':status', $status);  
        $stmt->execute();

        header('Location: list_cheque.php');
    } catch (PDOException $e) {
        echo "Error: " . $e->getMessage();
    }
}
?>
