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

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

if ($_SERVER['REQUEST_METHOD'] != 'POST') {
    header('Location: list_payments.php');
    exit();
}

$invoice_id = $_POST['invoice_id'] ?? '';
$amount = $_POST['amount'] ?? 0;
$payment_method = $_POST['payment_method'] ?? '';
$payment_reference = $_POST['payment_reference'] ?? '';
$mpesa_code = $_POST['mpesa_code'] ?? '';
$phone_number = $_POST['phone_number'] ?? '';
$reference_number = $_POST['reference_number'] ?? '';
$notes = $_POST['notes'] ?? '';

if (empty($invoice_id) || empty($amount) || empty($payment_method)) {
    $_SESSION['error_message'] = "Please fill in all required fields";
    header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? 'list_payments.php'));
    exit();
}

// Get invoice details
$sql_invoice = "SELECT * FROM invoices WHERE invoice_id = ?";
$stmt_invoice = $conn->prepare($sql_invoice);
$stmt_invoice->bind_param("i", $invoice_id);
$stmt_invoice->execute();
$result_invoice = $stmt_invoice->get_result();
$invoice = $result_invoice->fetch_assoc();

if (!$invoice) {
    $_SESSION['error_message'] = "Invoice not found";
    header('Location: list_payments.php');
    exit();
}

// Generate payment reference if not provided
if (empty($payment_reference)) {
    $payment_reference = 'PAY-' . date('Ymd') . '-' . strtoupper(substr(uniqid(), -8));
}

// Set payment status based on method
$payment_status = 'PENDING';
if ($payment_method == 'M-Pesa' && !empty($mpesa_code)) {
    $payment_status = 'COMPLETED';
    $payment_reference = $mpesa_code;
} elseif ($payment_method == 'Bank Transfer' && !empty($reference_number)) {
    $payment_status = 'PENDING'; // Needs verification
    $payment_reference = $reference_number;
} elseif ($payment_method == 'Cash') {
    $payment_status = 'COMPLETED';
}

// Insert payment
$sql = "INSERT INTO rent_payments (lease_id, invoice_id, amount, payment_date, payment_method, 
                                   payment_reference, payment_status, notes, created_at) 
        VALUES (?, ?, ?, NOW(), ?, ?, ?, ?, NOW())";

$stmt = $conn->prepare($sql);
$stmt->bind_param("iidssss", $invoice['lease_id'], $invoice_id, $amount, $payment_method, 
                 $payment_reference, $payment_status, $notes);

if ($stmt->execute()) {
    $payment_id = $conn->insert_id;
    
    // Update invoice balance
    $new_balance = max(0, $invoice['balance'] - $amount);
    $new_status = $new_balance == 0 ? 'paid' : ($new_balance < $invoice['total_amount'] ? 'partial' : $invoice['status']);
    
    $sql_update = "UPDATE invoices SET balance = ?, status = ? WHERE invoice_id = ?";
    $stmt_update = $conn->prepare($sql_update);
    $stmt_update->bind_param("dsi", $new_balance, $new_status, $invoice_id);
    $stmt_update->execute();
    
    $_SESSION['success_message'] = "Payment recorded successfully! Reference: " . $payment_reference;
    header('Location: payment_details.php?id=' . $payment_id);
    exit();
} else {
    $_SESSION['error_message'] = "Error recording payment: " . $conn->error;
    header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? 'list_payments.php'));
    exit();
}
?>
