<?php
session_start();
include_once 'shikanisha.kts.php';

$response = []; // To store the response

// Check if the request is POST
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $trans_id = $_POST['loanid'] ?? null;
    // Convert payment amounts to float values
    $payamount = floatval($_POST['payamount'] ?? 0);
    $paymethod = $_POST['paymethod'] ?? null;
    $payamount2 = floatval($_POST['payamount2'] ?? 0);
    $paymethod2 = $_POST['paymethod2'] ?? null;
    $sellername = $_SESSION['user'] ?? 'DefaultUser';
    $date = date('Y-m-d');
    $booking_id = intval($_POST['booking_id'] ?? 0);
    $totalpaid = $payamount2 + $payamount; // Now this will work with numbers

    // Begin transaction
    $conn->begin_transaction();

    try {
        // Get shift and employee information with FOR UPDATE lock
        $sql = "SELECT order_employee_id, shift_id, amount_received, total 
                FROM transaction_receipts 
                WHERE trans_id = ? FOR UPDATE";
        $stmt = $conn->prepare($sql);
        if (!$stmt) throw new Exception("Prepare failed: " . $conn->error);
        
        $stmt->bind_param("i", $trans_id);
        if (!$stmt->execute()) throw new Exception("Execute failed: " . $stmt->error);
        
        $result = $stmt->get_result();
        if ($result->num_rows === 0) throw new Exception("Transaction not found");
        
        $transaction = $result->fetch_assoc();
        $employee_id = $transaction['order_employee_id'];
        $shift_id = $transaction['shift_id'];
        $stmt->close();

        // Update transaction_receipts with the first payment
        $stmtUpdate = $conn->prepare("UPDATE `transaction_receipts` SET `amount_received` = `amount_received` + ? WHERE `trans_id` = ?");
        $stmtUpdate->bind_param("di", $payamount, $trans_id);

        if (!$stmtUpdate->execute()) {
            throw new Exception('Error updating transaction receipts: ' . $stmtUpdate->error);
        }
        $stmtUpdate->close();

        // Insert first payment into payments table
        $stmtInsert = $conn->prepare("INSERT INTO `payments` (`payment_method`, `trans_id`, `amount`) VALUES (?, ?, ?)");
        $stmtInsert->bind_param("sid", $paymethod, $trans_id, $payamount);

        if (!$stmtInsert->execute()) {
            throw new Exception('Error inserting first payment: ' . $stmtInsert->error);
        }

        // If there's a second payment, update and insert it
        if ($payamount2 > 0 && $paymethod2) {
            // Update transaction_receipts with the second payment
            $stmtUpdate = $conn->prepare("UPDATE `transaction_receipts` SET `amount_received` = `amount_received` + ? WHERE `trans_id` = ?");
            $stmtUpdate->bind_param("di", $payamount2, $trans_id);
            if (!$stmtUpdate->execute()) {
                throw new Exception('Error updating transaction receipts with second payment: ' . $stmtUpdate->error);
            }
            $stmtUpdate->close();

            // Insert second payment into payments table
            $stmtInsert->bind_param("sid", $paymethod2, $trans_id, $payamount2);
            if (!$stmtInsert->execute()) {
                throw new Exception('Error inserting second payment: ' . $stmtInsert->error);
            }
        }

        // If there's a booking_id, update room_bills
        if ($booking_id > 0) {
            $stmtUpdate = $conn->prepare("INSERT INTO `room_bills`(`trans_id`, `booking_id`, `amount`) VALUES (?, ?, ?)");
            $stmtUpdate->bind_param("iid", $trans_id, $booking_id, $payamount);
            
            if (!$stmtUpdate->execute()) {
                throw new Exception('Error updating room bills: ' . $stmtUpdate->error);
            }
            $stmtUpdate->close();
        }

        // Update shift totals
        $updateShift = $conn->prepare("UPDATE shifts SET 
                                     total_payments = total_payments + ?,
                                     total_debt = total_debt - ?
                                     WHERE shift_id = ?");
        $updateShift->bind_param("ddi", $totalpaid, $totalpaid, $shift_id);
        if (!$updateShift->execute()) {
            throw new Exception('Error updating shift totals: ' . $updateShift->error);
        }
        $updateShift->close();

        $stmtInsert->close();
        $conn->commit();
        
        $response['status'] = 'success';
        $response['message'] = 'Payments updated successfully';
    } catch (Exception $e) {
        $conn->rollback();
        $response['status'] = 'error';
        $response['message'] = $e->getMessage();
    }
} else {
    $response['status'] = 'error';
    $response['message'] = 'Invalid request method.';
}

echo json_encode($response);
?>