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

header('Content-Type: application/json');

try {
    // Check if user is logged in
    if (!isset($_SESSION['user_id'])) {
        throw new Exception('User not authenticated');
    }

    // Validate input
    $claim_no = $_POST['claim_no'] ?? '';
    $invoice_no = $_POST['invoice_no'] ?? '';
    $vet_status = (int)($_POST['vet_status'] ?? 0);
    $remarks = $_POST['remarks'] ?? null;
    $deduction_amount = floatval($_POST['deduction_amount'] ?? 0);
    $deduction_reason = (int)($_POST['deduction_reason'] ?? 0);
    $amount_payable = floatval($_POST['amount_payable'] ?? 0);
    $user_id = $_SESSION['user_id'];
    $is_reimbursement = isset($_POST['is_reimbursement']) && $_POST['is_reimbursement'] === 'true';

    if (empty($claim_no) || empty($invoice_no) || !in_array($vet_status, [1, 2, 3])) {
        throw new Exception('Invalid input parameters');
    }

    // Validate reason for reject/defer
    if (($vet_status === 2 || $vet_status === 3) && empty($remarks)) {
        throw new Exception('Remarks are required for rejection or deferral');
    }

    // Validate deduction reason if there's a deduction
    if ($deduction_amount > 0 && empty($deduction_reason)) {
        throw new Exception('Deduction reason is required when there is a deduction');
    }

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

    // Get bill details first
    $sql = "SELECT service, provider, invoiced_amount, is_reimbursement 
            FROM bills 
            WHERE claim_no = ? AND invoice_no = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('ss', $claim_no, $invoice_no);
    $stmt->execute();
    $result = $stmt->get_result();
    $bill = $result->fetch_assoc();

    if (!$bill) {
        throw new Exception('Invoice not found');
    }

    // Validate deduction amount
    if ($deduction_amount > $bill['invoiced_amount']) {
        throw new Exception('Deduction amount cannot be greater than invoice amount');
    }

    // Insert into bill_vet table
    $sql = "INSERT INTO bill_vet (
        claim_no,
        invoice_no,
        service,
        provider,
        vet_status,
        reasons,
        remarks,
        vet_datetime,
        user_id,
        date_entered
    ) VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), ?, CURDATE())";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param('ssiiiiss', 
        $claim_no,
        $invoice_no,
        $bill['service'],
        $bill['provider'],
        $vet_status,
        $deduction_reason,
        $remarks,
        $user_id
    );
    $stmt->execute();

    // Update specific invoice in bills table
    $sql = "UPDATE bills SET 
        vet_status = ?,
        deduction_amount = ?,
        deduction_reason = ?,
        amount_payable = ?";

    // Add reimbursement status update if it's a reimbursement
    if ($bill['is_reimbursement']) {
        $sql .= ", reimbursement_status = CASE 
            WHEN ? = 1 THEN 'PENDING'
            WHEN ? IN (2, 3) THEN 'REJECTED'
            ELSE reimbursement_status 
        END";
    }

    $sql .= " WHERE claim_no = ? AND invoice_no = ?";

    $stmt = $conn->prepare($sql);
    
    if ($bill['is_reimbursement']) {
        $stmt->bind_param('ididiiis', 
            $vet_status,
            $deduction_amount,
            $deduction_reason,
            $amount_payable,
            $vet_status,  // For reimbursement status check
            $vet_status,  // For reimbursement status check
            $claim_no,
            $invoice_no
        );
    } else {
        $stmt->bind_param('ididss', 
            $vet_status,
            $deduction_amount,
            $deduction_reason,
            $amount_payable,
            $claim_no,
            $invoice_no
        );
    }
    $stmt->execute();

    // Log the activity
    $action = '';
    switch ($vet_status) {
        case 1:
            $action = 'Approved';
            break;
        case 2:
            $action = 'Rejected';
            break;
        case 3:
            $action = 'Deferred';
            break;
    }

    $sql = "INSERT INTO activity_log (
        user_id,
        action,
        table_name,
        record_id,
        old_values,
        new_values,
        action_date,
        additional_info
    ) VALUES (?, ?, 'bills', ?, NULL, ?, NOW(), ?)";

    $stmt = $conn->prepare($sql);
    $new_values = json_encode([
        'vet_status' => $vet_status,
        'remarks' => $remarks,
        'deduction_amount' => $deduction_amount,
        'deduction_reason' => $deduction_reason,
        'amount_payable' => $amount_payable,
        'invoice_no' => $invoice_no,
        'is_reimbursement' => $bill['is_reimbursement']
    ]);
    
    $additional_info = ($bill['is_reimbursement'] ? "Reimbursement " : "") . 
                      "Invoice $invoice_no $action: " . ($remarks ?? 'No remarks');
    $action = 'UPDATE';
    
    $stmt->bind_param('sssss',
        $user_id,
        $action,
        $claim_no,
        $new_values,
        $additional_info
    );
    $stmt->execute();

    // Commit transaction
    $conn->commit();

    echo json_encode([
        'success' => true,
        'message' => 'Invoice has been vetted successfully',
        'is_reimbursement' => $bill['is_reimbursement']
    ]);

} catch (Exception $e) {
    // Rollback transaction if error occurs
    //if ($conn->inTransaction()) {
        $conn->rollback();
    //}

    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

$conn->close();
?>