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

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

// Check authentication
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 (!isset($data['claim_no']) || empty($data['claim_no'])) {
        throw new Exception('Claim number is required');
    }

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

    // Update reimbursement status
    $sql = "UPDATE bills SET 
            reimbursement_status = 'PAID',
            date_paid = CURDATE(),
            paid_by = ?
            WHERE claim_no = ? AND is_reimbursement = 1";

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

    $stmt->bind_param('ss', $_SESSION['user_id'], $data['claim_no']);

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

    if ($stmt->affected_rows === 0) {
        throw new Exception("No reimbursement found with claim number: " . $data['claim_no']);
    }

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

    $stmt = $conn->prepare($sql);
    
    $new_values = json_encode([
        'reimbursement_status' => 'PAID',
        'date_paid' => date('Y-m-d'),
        'paid_by' => $_SESSION['user_id']
    ]);
    
    $additional_info = 'Reimbursement marked as paid';

    $stmt->bind_param('ssssss',
        $_SESSION['user_id'],
        $data['claim_no'],
        $new_values,
        $_SERVER['REMOTE_ADDR'],
        $_SERVER['HTTP_USER_AGENT'],
        $additional_info
    );

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

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

    echo json_encode([
        'success' => true,
        'message' => 'Reimbursement marked as paid successfully'
    ]);

} catch (Exception $e) {
    if ($conn->inTransaction()) {
        $conn->rollback();
    }
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

$conn->close();
?>