<?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['status'])
) {
    Response::error('Valid lead_id and status are required', 422);
}

$leadId = (int)$data['lead_id'];
$newStatus = $data['status'];
$newPriority = $data['priority'] ?? null;

/**
 * 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', 'Executive', 'Manager'], true)) {
    Response::error('You are not authorized to update lead status', 403);
}

/**
 * Validate status
 */
$allowedStatuses = [
    'New',
    'Contacted',
    'Qualified',
    'Not Interested',
    'Converted',
    'Closed'
];

if (!in_array($newStatus, $allowedStatuses, true)) {
    Response::error('Invalid lead status', 422);
}

/**
 * Validate priority (optional)
 */
if ($newPriority !== null) {
    $allowedPriority = ['Low', 'Medium', 'High'];
    if (!in_array($newPriority, $allowedPriority, true)) {
        Response::error('Invalid priority', 422);
    }
}

/**
 * Fetch existing lead
 */
$stmt = $db->prepare("
    SELECT status, priority
    FROM leads
    WHERE id = :id
");
$stmt->execute(['id' => $leadId]);
$lead = $stmt->fetch();

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

$oldStatus = $lead['status'];
$oldPriority = $lead['priority'];

/**
 * No-op check
 */
if ($oldStatus === $newStatus && $newPriority === null) {
    Response::error('No changes detected', 409);
}

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

try {

    /**
     * Update lead
     */
    $updateFields = ['status = :status', 'updated_at = NOW()'];
    $params = [
        'status' => $newStatus,
        'id'     => $leadId
    ];

    if ($newPriority !== null) {
        $updateFields[] = 'priority = :priority';
        $params['priority'] = $newPriority;
    }

    $sql = "
        UPDATE leads
        SET " . implode(', ', $updateFields) . "
        WHERE id = :id
    ";

    $stmt = $db->prepare($sql);
    $stmt->execute($params);

    /**
     * Log status change
     */
    $stmt = $db->prepare("
        INSERT INTO lead_activity_log (
            lead_id,
            action,
            old_value,
            new_value,
            performed_by,
            performed_at
        ) VALUES (
            :lead_id,
            'status_change',
            :old_value,
            :new_value,
            :performed_by,
            NOW()
        )
    ");

    $stmt->execute([
        'lead_id'      => $leadId,
        'old_value'    => $oldStatus,
        'new_value'    => $newStatus,
        'performed_by'=> $_SESSION['employee_id']
    ]);

    /**
     * Log priority change (if any)
     */
    if ($newPriority !== null && $oldPriority !== $newPriority) {
        $stmt = $db->prepare("
            INSERT INTO lead_activity_log (
                lead_id,
                action,
                old_value,
                new_value,
                performed_by,
                performed_at
            ) VALUES (
                :lead_id,
                'priority_change',
                :old_value,
                :new_value,
                :performed_by,
                NOW()
            )
        ");
        $stmt->execute([
            'lead_id'      => $leadId,
            'old_value'    => $oldPriority,
            'new_value'    => $newPriority,
            'performed_by'=> $_SESSION['employee_id']
        ]);
    }

    $db->commit();

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

Response::success('Lead status updated successfully');
