<?php
session_start();
header('Content-Type: application/json');

include '../layouts/dbconn.php';

// Check authentication
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

// Check permissions
$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    echo json_encode(['success' => false, 'message' => 'Insufficient permissions']);
    exit();
}

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

if (!isset($input['claim_id']) || !isset($input['action'])) {
    echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
    exit();
}

$claim_id = (int)$input['claim_id'];
$action = $input['action'];
$user_id = $_SESSION['user_id'];

$conn->begin_transaction();

try {
    if ($action === 'approve') {
        $approved_amount = isset($input['approved_amount']) ? (float)$input['approved_amount'] : 0;
        $notes = isset($input['notes']) ? trim($input['notes']) : '';
        
        if ($approved_amount <= 0) {
            throw new Exception('Invalid approved amount');
        }
        
        // Update claim status
        $update_sql = "UPDATE insurance_claims SET
                      claim_status = 'APPROVED',
                      approved_amount = ?,
                      approval_date = CURDATE(),
                      notes = CONCAT(COALESCE(notes, ''), '\n[', NOW(), '] Approved by ', ?, ': ', ?),
                      processed_by = ?,
                      updated_at = NOW()
                    WHERE claim_id = ?";
        
        $stmt = $conn->prepare($update_sql);
        $user_name = $_SESSION['full_name'];
        $stmt->bind_param('dssi', $approved_amount, $user_name, $notes, $user_id, $claim_id);
        
        if (!$stmt->execute()) {
            throw new Exception('Failed to approve claim');
        }
        
        // Log activity
        $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, ip_address, logged_at)
                   VALUES (?, 'APPROVE', 'INSURANCE_CLAIMS', ?, 'CLAIM', ?, NOW())";
        $log_stmt = $conn->prepare($log_sql);
        $ip_address = $_SERVER['REMOTE_ADDR'];
        $log_stmt->bind_param('iis', $user_id, $claim_id, $ip_address);
        $log_stmt->execute();
        
        $conn->commit();
        echo json_encode(['success' => true, 'message' => 'Claim approved successfully']);
        
    } elseif ($action === 'reject') {
        $rejection_reason = isset($input['rejection_reason']) ? trim($input['rejection_reason']) : '';
        
        if (empty($rejection_reason)) {
            throw new Exception('Rejection reason is required');
        }
        
        // Update claim status
        $update_sql = "UPDATE insurance_claims SET
                      claim_status = 'REJECTED',
                      rejection_reason = ?,
                      notes = CONCAT(COALESCE(notes, ''), '\n[', NOW(), '] Rejected by ', ?),
                      processed_by = ?,
                      updated_at = NOW()
                    WHERE claim_id = ?";
        
        $stmt = $conn->prepare($update_sql);
        $user_name = $_SESSION['full_name'];
        $stmt->bind_param('ssii', $rejection_reason, $user_name, $user_id, $claim_id);
        
        if (!$stmt->execute()) {
            throw new Exception('Failed to reject claim');
        }
        
        // Log activity
        $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, ip_address, logged_at)
                   VALUES (?, 'REJECT', 'INSURANCE_CLAIMS', ?, 'CLAIM', ?, NOW())";
        $log_stmt = $conn->prepare($log_sql);
        $ip_address = $_SERVER['REMOTE_ADDR'];
        $log_stmt->bind_param('iis', $user_id, $claim_id, $ip_address);
        $log_stmt->execute();
        
        $conn->commit();
        echo json_encode(['success' => true, 'message' => 'Claim rejected successfully']);
        
    } else {
        throw new Exception('Invalid action');
    }
    
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>