<?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)) {
    Response::error('Valid lead_id is required', 422);
}

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

/**
 * 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 leads', 403);
}

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

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

/**
 * Allowed fields to update
 */
$allowedFields = [
    'name',
    'phone',
    'email',
    'city',
    'state',
    'pincode',
    'message',
    'product_purpose',
    'priority',
    'source_type',
    'source_id',
    'source_slug',
    'source_url'
];

$updates = [];
$params  = ['id' => $leadId];

/**
 * Validate & build updates
 */
foreach ($allowedFields as $field) {
    if (array_key_exists($field, $data)) {

        $newValue = $data[$field];
        $oldValue = $existing[$field];

        if ($newValue === $oldValue) {
            continue;
        }

        // Field-level validation
        if ($field === 'phone' && !preg_match('/^[0-9]{10,15}$/', $newValue)) {
            Response::error('Invalid phone number', 422);
        }

        if ($field === 'email' && $newValue !== null && !filter_var($newValue, FILTER_VALIDATE_EMAIL)) {
            Response::error('Invalid email', 422);
        }

        if ($field === 'product_purpose' && !in_array($newValue, ['Home', 'Hotel'], true)) {
            Response::error('Invalid product purpose', 422);
        }

        if ($field === 'priority' && !in_array($newValue, ['Low','Medium','High'], true)) {
            Response::error('Invalid priority', 422);
        }

        $updates[] = "$field = :$field";
        $params[$field] = $newValue;

        /**
         * Log field change
         */
        $db->prepare("
            INSERT INTO lead_activity_log (
                lead_id,
                action,
                old_value,
                new_value,
                performed_by,
                performed_at
            ) VALUES (
                :lead_id,
                'field_update',
                :old_value,
                :new_value,
                :performed_by,
                NOW()
            )
        ")->execute([
            'lead_id'      => $leadId,
            'old_value'    => (string)$oldValue,
            'new_value'    => (string)$newValue,
            'performed_by'=> $_SESSION['employee_id']
        ]);
    }
}

/**
 * Nothing to update
 */
if (empty($updates)) {
    Response::error('No changes detected', 409);
}

/**
 * Update lead
 */
$sql = "
    UPDATE leads
    SET " . implode(', ', $updates) . ",
        updated_at = NOW()
    WHERE id = :id
";

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

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