<?php
session_start();
require_once '../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();
}

// Check if required parameters are provided
if (!isset($_POST['caregiver_id']) || !isset($_POST['certification_id'])) {
    echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
    exit();
}

$caregiver_id = intval($_POST['caregiver_id']);
$certification_id = intval($_POST['certification_id']);
$user_id = $_SESSION['user_id'];

try {
    // Check if certification exists
    $check_query = "SELECT cc.*, c.certification_name 
                    FROM caregiver_certifications cc
                    JOIN certifications c ON cc.certification_id = c.certification_id
                    WHERE cc.caregiver_id = ? AND cc.certification_id = ?";
    $stmt = $conn->prepare($check_query);
    $stmt->bind_param("ii", $caregiver_id, $certification_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        throw new Exception('Certification not found');
    }
    
    $cert = $result->fetch_assoc();
    
    // Delete the certification
    $delete_query = "DELETE FROM caregiver_certifications 
                     WHERE caregiver_id = ? AND certification_id = ?";
    $stmt = $conn->prepare($delete_query);
    $stmt->bind_param("ii", $caregiver_id, $certification_id);
    $stmt->execute();
    
    // Log the deletion
    $audit_log = "INSERT INTO audit_log (user_id, action_type, entity_type, entity_id, description, ip_address, status) 
                  VALUES (?, 'DELETE', 'caregiver_certifications', ?, ?, ?, 'SUCCESS')";
    $stmt = $conn->prepare($audit_log);
    $description = "Deleted certification '{$cert['certification_name']}' from caregiver ID: {$caregiver_id}";
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $stmt->bind_param("iiss", $user_id, $caregiver_id, $description, $ip_address);
    $stmt->execute();
    
    echo json_encode([
        'success' => true,
        'message' => 'Certification deleted successfully'
    ]);
    
} catch (Exception $e) {
    // Log the error
    $audit_log = "INSERT INTO audit_log (user_id, action_type, entity_type, entity_id, description, ip_address, status) 
                  VALUES (?, 'DELETE', 'caregiver_certifications', ?, ?, ?, 'FAILED')";
    $stmt = $conn->prepare($audit_log);
    $description = "Failed to delete certification from caregiver ID: {$caregiver_id}. Error: " . $e->getMessage();
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $stmt->bind_param("iiss", $user_id, $caregiver_id, $description, $ip_address);
    $stmt->execute();
    
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

$conn->close();
?>