<?php
include 'layouts/dbconn.php'; // Database connection
// Set header to return JSON
header('Content-Type: application/json');

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $conn->begin_transaction();
    try {
        // Get form data
        $bookingId = intval($_POST['booking_id']);
        $amount = floatval($_POST['amount']);
        $selectedPaymentMethod = $_POST['selected_payment_method'];
        $paymentStatus = $_POST['payment_status'];
        $transactionId = isset($_POST['transaction_id']) ? $_POST['transaction_id'] : null;
        $paymentDate = isset($_POST['payment_date']) ? $_POST['payment_date'] : date('Y-m-d');

        // Set payment method and payment gateway
        $paymentMethod = $selectedPaymentMethod;
        $paymentGateway = ($selectedPaymentMethod === 'Credit Card') ? 'Credit Card Gateway' : 'Cash';

        $gatewayTransactionId = null;
        $gatewayResponse = null;

        // For credit card payments, we might want to capture additional details
        if ($selectedPaymentMethod === 'Credit Card') {
            $gatewayTransactionId = isset($_POST['cc_transaction_id']) ? $_POST['cc_transaction_id'] : null;
            $gatewayResponse = isset($_POST['cc_response']) ? $_POST['cc_response'] : null;
        }

        // Validate form data
        if ($amount <= 0) {
            throw new Exception("Amount must be greater than zero.");
        }

        // Fetch the current total amount and total paid from the bookings table
        $balanceStmt = $conn->prepare("SELECT total_amount, COALESCE(SUM(p.amount), 0) as total_paid 
                                       FROM bookings b
                                       LEFT JOIN payments p ON b.booking_id = p.booking_id
                                       WHERE b.booking_id = ?
                                       GROUP BY b.booking_id");
        $balanceStmt->bind_param("i", $bookingId);
        $balanceStmt->execute();
        $balanceResult = $balanceStmt->get_result();
        $bookingData = $balanceResult->fetch_assoc();
        $totalAmount = $bookingData['total_amount'];
        $totalPaid = $bookingData['total_paid'];
        $balanceStmt->close();

        // Calculate the new remaining balance
        $newTotalPaid = $totalPaid + $amount;
        $newRemainingBalance = $totalAmount - $newTotalPaid;
        
       // error_log("Payment Status: $paymentStatus");

        // Insert payment data into the payments table
        $stmt = $conn->prepare("INSERT INTO payments (booking_id, amount, payment_date, payment_status, payment_method, transaction_id, payment_gateway, gateway_transaction_id, gateway_response) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("idsssssss", $bookingId, $amount, $paymentDate, $paymentStatus, $paymentMethod, $transactionId, $paymentGateway, $gatewayTransactionId, $gatewayResponse);
        $stmt->execute();
        $paymentId = $conn->insert_id;

        // Determine the new payment status
        $newPaymentStatus = 'Partially Paid';
        if ($newRemainingBalance <= 0) {
            $newPaymentStatus = 'Fully Paid';
        }

        // Update the booking's payment status and remaining balance
        $updateStmt = $conn->prepare("UPDATE bookings SET payment_status = ?, remaining_balance = ? WHERE booking_id = ?");
        $updateStmt->bind_param("sdi", $newPaymentStatus, $newRemainingBalance, $bookingId);
        $updateStmt->execute();

        $conn->commit();

        // Prepare the response
        $response = [
            'status' => 'success',
            'message' => 'Payment saved successfully!',
            'payment_id' => $paymentId,
            'redirect' => 'all_payments.php'
        ];

        echo json_encode($response);
    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(['status' => 'error', 'message' => 'Error: ' . $e->getMessage()]);
    }
    if (isset($stmt)) $stmt->close();
    if (isset($updateStmt)) $updateStmt->close();
}
$conn->close();
?>