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

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

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

$user_id = $_SESSION['user_id'];

// Validate input
if (!isset($_POST['client_id']) || empty($_POST['client_id'])) {
    echo json_encode(['success' => false, 'message' => 'Client ID is required']);
    exit();
}

$client_id = intval($_POST['client_id']);

try {
    // Start transaction
    $conn->begin_transaction();
    
    // Get client details before deletion for logging
    $select_sql = "SELECT client_number, personal_info FROM clients WHERE client_id = ?";
    $select_stmt = $conn->prepare($select_sql);
    $select_stmt->bind_param("i", $client_id);
    $select_stmt->execute();
    $result = $select_stmt->get_result();
    
    if ($result->num_rows === 0) {
        $conn->rollback();
        echo json_encode(['success' => false, 'message' => 'Client not found']);
        exit();
    }
    
    $client_data = $result->fetch_assoc();
    $client_number = $client_data['client_number'];
    $personal_info = json_decode($client_data['personal_info'], true);
    $client_name = $personal_info['full_name'] ?? 'Unknown';
    
    // Check for active contracts
    $contract_check = "SELECT COUNT(*) as active_contracts 
                       FROM client_contracts 
                       WHERE client_id = ? AND status = 'active'";
    $contract_stmt = $conn->prepare($contract_check);
    $contract_stmt->bind_param("i", $client_id);
    $contract_stmt->execute();
    $contract_result = $contract_stmt->get_result()->fetch_assoc();
    
    if ($contract_result['active_contracts'] > 0) {
        $conn->rollback();
        echo json_encode([
            'success' => false, 
            'message' => 'Cannot delete client with active contracts. Please terminate contracts first.'
        ]);
        exit();
    }
    
    // Check for future schedules
    $schedule_check = "SELECT COUNT(*) as future_schedules 
                       FROM schedules 
                       WHERE client_id = ? 
                       AND shift_date >= CURDATE() 
                       AND status IN ('scheduled', 'confirmed')";
    $schedule_stmt = $conn->prepare($schedule_check);
    $schedule_stmt->bind_param("i", $client_id);
    $schedule_stmt->execute();
    $schedule_result = $schedule_stmt->get_result()->fetch_assoc();
    
    if ($schedule_result['future_schedules'] > 0) {
        $conn->rollback();
        echo json_encode([
            'success' => false, 
            'message' => 'Cannot delete client with upcoming schedules. Please cancel schedules first.'
        ]);
        exit();
    }
    
    // Delete the client (triggers will handle audit logging)
    $delete_sql = "DELETE FROM clients WHERE client_id = ?";
    $delete_stmt = $conn->prepare($delete_sql);
    $delete_stmt->bind_param("i", $client_id);
    
    if ($delete_stmt->execute()) {
        // Additional audit log entry
        $audit_sql = "INSERT INTO audit_log (
            user_id, action_type, entity_type, entity_id,
            description, ip_address, status, created_at
        ) VALUES (?, 'DELETE', 'clients', ?, ?, ?, 'SUCCESS', NOW())";
        
        $audit_stmt = $conn->prepare($audit_sql);
        $description = "Deleted client: " . $client_number . " (" . $client_name . ")";
        $ip_address = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
        
        $audit_stmt->bind_param("iiss", 
            $user_id, 
            $client_id, 
            $description, 
            $ip_address
        );
        $audit_stmt->execute();
        
        // Commit transaction
        $conn->commit();
        
        echo json_encode([
            'success' => true,
            'message' => 'Client deleted successfully'
        ]);
    } else {
        $conn->rollback();
        echo json_encode([
            'success' => false,
            'message' => 'Failed to delete client: ' . $delete_stmt->error
        ]);
    }
    
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}

$conn->close();
?>