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

// Set content type to JSON
header('Content-Type: application/json');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'User not authenticated']);
    exit();
}

// Check if it's a POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

$user_id = $_SESSION['user_id'];
$customer_id = isset($_POST['customer_id']) ? (int)$_POST['customer_id'] : 0;

if (!$customer_id) {
    echo json_encode(['success' => false, 'message' => 'Invalid customer ID']);
    exit();
}

try {
    // Check if customer exists and is not already verified
    $check_sql = "SELECT customer_id, kyc_status, first_name, last_name FROM customers WHERE customer_id = ?";
    $check_stmt = $conn->prepare($check_sql);
    $check_stmt->bind_param("i", $customer_id);
    $check_stmt->execute();
    $customer = $check_stmt->get_result()->fetch_assoc();
    $check_stmt->close();

    if (!$customer) {
        echo json_encode(['success' => false, 'message' => 'Customer not found']);
        exit();
    }

    if ($customer['kyc_status'] === 'VERIFIED') {
        echo json_encode(['success' => false, 'message' => 'Customer KYC is already verified']);
        exit();
    }

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

    // Update customer KYC status
    $update_sql = "UPDATE customers SET 
                   kyc_status = 'VERIFIED', 
                   kyc_verified_by = ?, 
                   kyc_verified_at = NOW(),
                   updated_at = NOW()
                   WHERE customer_id = ?";
    
    $update_stmt = $conn->prepare($update_sql);
    $update_stmt->bind_param("ii", $user_id, $customer_id);
    
    if (!$update_stmt->execute()) {
        throw new Exception('Failed to update KYC status');
    }
    $update_stmt->close();

    // Log the activity
    $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, new_values, ip_address, logged_at) 
               VALUES (?, 'KYC_VERIFY', 'CUSTOMER', ?, 'CUSTOMER', ?, ?, NOW())";
    
    $log_stmt = $conn->prepare($log_sql);
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $log_data = json_encode([
        'customer_name' => $customer['first_name'] . ' ' . $customer['last_name'],
        'previous_status' => $customer['kyc_status'],
        'new_status' => 'VERIFIED',
        'verified_by' => $user_id
    ]);
    
    $log_stmt->bind_param("iiss", $user_id, $customer_id, $log_data, $ip_address);
    $log_stmt->execute();
    $log_stmt->close();

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

    echo json_encode([
        'success' => true, 
        'message' => 'Customer KYC verified successfully',
        'customer_name' => $customer['first_name'] . ' ' . $customer['last_name']
    ]);

} catch (Exception $e) {
    // Rollback transaction
    if ($conn->connect_errno === 0) {
        $conn->rollback();
    }
    
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

$conn->close();
?>