<?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();

/**
 * Validate lead_id
 */
if (empty($_GET['id']) || !filter_var($_GET['id'], FILTER_VALIDATE_INT)) {
    Response::error('Valid lead id is required', 422);
}

$leadId = (int)$_GET['id'];

/**
 * Fetch lead (FULL)
 */
$stmt = $db->prepare("
SELECT
    l.id,
    l.name,
    l.phone,
    l.email,
    l.pincode,
    l.city,
    l.state,
    l.message,

    l.product_purpose,

    l.status,
    l.priority,

    l.assigned_to,
    l.assigned_at,

    e.first_name AS assigned_first_name,
    e.last_name  AS assigned_last_name,

    l.source_type,
    l.source_id,
    l.source_slug,
    l.source_url,
    l.referrer_url,

    l.utm_source,
    l.utm_medium,
    l.utm_campaign,

    l.ip_address,
    l.user_agent,

    l.created_at,
    l.updated_at

FROM leads l
LEFT JOIN employees e ON e.id = l.assigned_to
WHERE l.id = :id
LIMIT 1
");
$stmt->execute(['id' => $leadId]);
$lead = $stmt->fetch();

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

/**
 * Fetch notes
 */
$stmt = $db->prepare("
SELECT
    n.id,
    n.note,
    n.created_at,
    emp.first_name,
    emp.last_name
FROM lead_notes n
JOIN employees emp ON emp.id = n.created_by
WHERE n.lead_id = :lead_id
ORDER BY n.created_at DESC
");
$stmt->execute(['lead_id' => $leadId]);
$notes = $stmt->fetchAll();

/**
 * Fetch activity log
 */
$stmt = $db->prepare("
SELECT
    a.id,
    a.action,
    a.old_value,
    a.new_value,
    a.performed_at,

    emp.first_name,
    emp.last_name
FROM lead_activity_log a
LEFT JOIN employees emp ON emp.id = a.performed_by
WHERE a.lead_id = :lead_id
ORDER BY a.performed_at DESC
");
$stmt->execute(['lead_id' => $leadId]);
$activity = $stmt->fetchAll();

/**
 * Response
 */
Response::success('Lead fetched successfully', [
    'lead'     => $lead,
    'notes'    => $notes,
    'activity' => $activity
]);
