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

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

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['error' => 'Not authenticated']);
    exit;
}

try {
    $data = json_decode(file_get_contents('php://input'), true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('Invalid JSON data received: ' . json_last_error_msg());
    }

    // Validate required fields
    $required_fields = [
        'member_no', 'corp_id', 'family_no', 'invoice_date', 
        'provider', 'bank_code', 'account_no', 'account_name'
    ];

    foreach ($required_fields as $field) {
        if (!isset($data[$field]) || empty($data[$field])) {
            throw new Exception("Missing required field: $field");
        }
    }

    if (empty($data['claims']) || !is_array($data['claims'])) {
        throw new Exception('No claim lines provided');
    }

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

    // Generate claim number
    $sql = "SELECT MAX(CAST(SUBSTRING(claim_no, 5) AS UNSIGNED)) as max_num 
            FROM bills WHERE claim_no LIKE 'RMB-%'";
    $result = $conn->query($sql);
    $row = $result->fetch_assoc();
    $next_num = ($row['max_num'] ?? 0) + 1;
    $claim_no = 'RMB-' . str_pad($next_num, 6, '0', STR_PAD_LEFT);

    // Insert each claim line
    foreach ($data['claims'] as $claim) {
        $sql = "INSERT INTO bills (
            claim_no,              -- 1. string
            claim_form_no,         -- 2. string
            invoice_no,            -- 3. string
            service,               -- 4. string
            provider,              -- 5. string
            member_no,             -- 6. string
            claim_nature,          -- 7. string
            invoice_date,          -- 8. string (date)
            invoiced_amount,       -- 9. double
            date_received,         -- 10. string (date)
            user_id,               -- 11. string
            date_entered,          -- 12. string (date)
            corp_id,               -- 13. string
            family_no,             -- 14. string
            pri_dep,               -- 15. string
            is_reimbursement,      -- 16. integer
            reimbursement_bank,    -- 17. string
            reimbursement_account, -- 18. string
            reimbursement_account_name, -- 19. string
            reimbursement_status   -- 20. string
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        $stmt = $conn->prepare($sql);
        if (!$stmt) {
            throw new Exception("Failed to prepare statement: " . $conn->error);
        }

        // Initialize all variables before binding
        $invoice_no = $claim_no . '-' . str_pad($claim['benefit_code'], 2, '0', STR_PAD_LEFT);
        $pri_dep = $data['pri_dep'] ?? 1;
        $is_reimbursement = 1;
        $reimbursement_status = 'PENDING';
        $user_id = $_SESSION['user_id'];
        $current_date = date('Y-m-d'); // Current date for date_received and date_entered

        // Bind exactly 20 parameters - match the types string with the number of parameters
        $stmt->bind_param(
            'ssssssssdsssssisssss',  // 20 parameters: 18 strings, 1 double, 1 integer
            $claim_no,              // 1. s - string
            $claim_no,              // 2. s - string
            $invoice_no,            // 3. s - string
            $claim['service_code'], // 4. s - string
            $data['provider'],      // 5. s - string
            $data['member_no'],     // 6. s - string
            $claim['benefit_code'], // 7. s - string
            $data['invoice_date'],  // 8. s - string (date)
            $claim['amount'],       // 9. d - double
            $current_date,          // 10. s - string (date_received)
            $user_id,               // 11. s - string
            $current_date,          // 12. s - string (date_entered)
            $data['corp_id'],       // 13. s - string
            $data['family_no'],     // 14. s - string
            $pri_dep,               // 15. s - string
            $is_reimbursement,      // 16. i - integer
            $data['bank_code'],     // 17. s - string
            $data['account_no'],    // 18. s - string
            $data['account_name'],  // 19. s - string
            $reimbursement_status   // 20. s - string
        );

        if (!$stmt->execute()) {
            throw new Exception("Failed to save claim line: " . $stmt->error);
        }
    }

    // Log the activity
    $log_sql = "INSERT INTO activity_log (
        user_id, action, table_name, record_id, new_values, 
        ip_address, user_agent, action_date, additional_info
    ) VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), ?)";

    $log_stmt = $conn->prepare($log_sql);
    $action = 'CREATE';
    $table = 'bills';
    $new_values = json_encode([
        'claim_no' => $claim_no,
        'member_no' => $data['member_no'],
        'corp_id' => $data['corp_id'],
        'total_amount' => array_sum(array_column($data['claims'], 'amount')),
        'reimbursement_details' => [
            'bank' => $data['bank_code'],
            'account' => $data['account_no']
        ]
    ]);
    
    $additional_info = 'Reimbursement claim created';
    
    $log_stmt->bind_param('ssssssss',
        $_SESSION['user_id'],
        $action,
        $table,
        $claim_no,
        $new_values,
        $_SERVER['REMOTE_ADDR'],
        $_SERVER['HTTP_USER_AGENT'],
        $additional_info
    );

    if (!$log_stmt->execute()) {
        throw new Exception("Failed to log activity: " . $log_stmt->error);
    }

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

    echo json_encode([
        'success' => true,
        'claim_no' => $claim_no,
        'message' => 'Reimbursement saved successfully'
    ]);

} catch (Exception $e) {
    if ($conn->inTransaction()) {
        $conn->rollback();
    }
    error_log("Reimbursement error: " . $e->getMessage());
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

$conn->close();
?>