<?php
session_start();
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$payment_id = $_GET['id'] ?? '';

if (empty($payment_id)) {
    header('Location: bank_reconciliation.php');
    exit();
}

// Get payment details
$sql = "SELECT * FROM rent_payments WHERE payment_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $payment_id);
$stmt->execute();
$result = $stmt->get_result();
$payment = $result->fetch_assoc();

if (!$payment) {
    header('Location: bank_reconciliation.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action == 'verify') {
        // Verify payment
        $sql_update = "UPDATE rent_payments SET payment_status = 'COMPLETED' WHERE payment_id = ?";
        $stmt_update = $conn->prepare($sql_update);
        $stmt_update->bind_param("i", $payment_id);
        
        if ($stmt_update->execute()) {
            // Update invoice balance
            if ($payment['invoice_id']) {
                $sql_invoice = "SELECT * FROM invoices WHERE invoice_id = ?";
                $stmt_invoice = $conn->prepare($sql_invoice);
                $stmt_invoice->bind_param("i", $payment['invoice_id']);
                $stmt_invoice->execute();
                $result_invoice = $stmt_invoice->get_result();
                $invoice = $result_invoice->fetch_assoc();
                
                if ($invoice) {
                    $new_balance = max(0, $invoice['balance'] - $payment['amount']);
                    $new_status = $new_balance == 0 ? 'paid' : ($new_balance < $invoice['total_amount'] ? 'partial' : $invoice['status']);
                    
                    $sql_update_invoice = "UPDATE invoices SET balance = ?, status = ? WHERE invoice_id = ?";
                    $stmt_update_invoice = $conn->prepare($sql_update_invoice);
                    $stmt_update_invoice->bind_param("dsi", $new_balance, $new_status, $payment['invoice_id']);
                    $stmt_update_invoice->execute();
                }
            }
            
            $_SESSION['success_message'] = "Payment verified successfully!";
            header('Location: bank_reconciliation.php');
            exit();
        }
    } elseif ($action == 'reject') {
        // Reject payment
        $sql_update = "UPDATE rent_payments SET payment_status = 'FAILED' WHERE payment_id = ?";
        $stmt_update = $conn->prepare($sql_update);
        $stmt_update->bind_param("i", $payment_id);
        $stmt_update->execute();
        
        $_SESSION['success_message'] = "Payment rejected";
        header('Location: bank_reconciliation.php');
        exit();
    }
}
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Verify Payment')); ?>
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Payments', 'title' => 'Verify Payment')); ?>

                    <div class="row mb-3">
                        <div class="col-12">
                            <a href="bank_reconciliation.php" class="btn btn-light">
                                <i class="ri-arrow-left-line me-1"></i>Back to Reconciliation
                            </a>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-8">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Verify Payment</h4>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <p><strong>Reference:</strong> <?php echo htmlspecialchars($payment['payment_reference']); ?></p>
                                        <p><strong>Amount:</strong> KES <?php echo number_format($payment['amount'], 2); ?></p>
                                        <p><strong>Method:</strong> <?php echo htmlspecialchars($payment['payment_method']); ?></p>
                                        <p><strong>Date:</strong> <?php echo date('M d, Y', strtotime($payment['payment_date'])); ?></p>
                                    </div>

                                    <form method="POST">
                                        <div class="alert alert-warning">
                                            <strong>Warning:</strong> Verifying this payment will update the invoice balance and mark it as completed.
                                        </div>
                                        
                                        <div class="mt-4">
                                            <button type="submit" name="action" value="verify" class="btn btn-success">
                                                <i class="ri-check-line me-1"></i>Verify Payment
                                            </button>
                                            <button type="submit" name="action" value="reject" class="btn btn-danger ms-2">
                                                <i class="ri-close-line me-1"></i>Reject Payment
                                            </button>
                                            <a href="bank_reconciliation.php" class="btn btn-light ms-2">
                                                Cancel
                                            </a>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
