<?php
declare(strict_types=1);

require_once __DIR__ . '/../../security/auth_guard.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../core/Response.php';

$db = Database::getInstance();

/**
 * Read input
 */
$data = json_decode(file_get_contents('php://input'), true);

if (
    empty($data['lead_id']) ||
    !filter_var($data['lead_id'], FILTER_VALIDATE_INT) ||
    empty($data['assigned_to']) ||
    !filter_var($data['assigned_to'], FILTER_VALIDATE_INT)
) {
    Response::error('Valid lead_id and assigned_to are required', 422);
}

$leadId      = (int)$data['lead_id'];
$assignedTo  = (int)$data['assigned_to'];

/**
 * Role check
 */
$stmt = $db->prepare("
    SELECT r.name
    FROM employees e
    JOIN roles r ON r.id = e.role_id
    WHERE e.id = :id
");
$stmt->execute(['id' => $_SESSION['employee_id']]);
$role = $stmt->fetchColumn();

if (!in_array($role, ['Super Admin', 'Admin', 'Manager'], true)) {
    Response::error('You are not authorized to assign leads', 403);
}

/**
 * Check lead exists
 */
$stmt = $db->prepare("
    SELECT assigned_to
    FROM leads
    WHERE id = :id
");
$stmt->execute(['id' => $leadId]);
$lead = $stmt->fetch();

if (!$lead) {
    Response::error('Lead not found', 404);
}

$oldAssignedTo = $lead['assigned_to'];

/**
 * Check employee exists & active
 */
$stmt = $db->prepare("
    SELECT id
    FROM employees
    WHERE id = :id AND status = 'active'
");
$stmt->execute(['id' => $assignedTo]);

if (!$stmt->fetch()) {
    Response::error('Invalid or inactive employee', 422);
}

/**
 * Transaction
 */
$db->beginTransaction();

try {

    /**
     * Assign lead
     */
    $stmt = $db->prepare("
        UPDATE leads
        SET
            assigned_to = :assigned_to,
            assigned_at = NOW(),
            updated_at = NOW()
        WHERE id = :id
    ");
    $stmt->execute([
        'assigned_to' => $assignedTo,
        'id'          => $leadId
    ]);

    /**
     * Log activity
     */
    $stmt = $db->prepare("
        INSERT INTO lead_activity_log (
            lead_id,
            action,
            old_value,
            new_value,
            performed_by,
            performed_at
        ) VALUES (
            :lead_id,
            'assign',
            :old_value,
            :new_value,
            :performed_by,
            NOW()
        )
    ");
    $stmt->execute([
        'lead_id'      => $leadId,
        'old_value'    => $oldAssignedTo,
        'new_value'    => $assignedTo,
        'performed_by'=> $_SESSION['employee_id']
    ]);

    $db->commit();

} catch (Throwable $e) {
    $db->rollBack();
    Response::error('Failed to assign lead', 500);
}

Response::success('Lead assigned successfully');
