<?php
declare(strict_types=1);

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

$db = Database::getInstance();

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

Validator::required($data, ['lead_id', 'note']);

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

Validator::minLength($note, 3, 'note');

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

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

if (!$stmt->fetch()) {
    Response::error('Lead not found', 404);
}

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

try {

    /**
     * Insert note
     */
    $stmt = $db->prepare("
        INSERT INTO lead_notes (
            lead_id,
            note,
            created_by,
            created_at
        ) VALUES (
            :lead_id,
            :note,
            :created_by,
            NOW()
        )
    ");
    $stmt->execute([
        'lead_id'    => $leadId,
        'note'       => $note,
        'created_by' => $_SESSION['employee_id']
    ]);

    /**
     * Log activity
     */
    $stmt = $db->prepare("
        INSERT INTO lead_activity_log (
            lead_id,
            action,
            old_value,
            new_value,
            performed_by,
            performed_at
        ) VALUES (
            :lead_id,
            'note_added',
            NULL,
            :note,
            :performed_by,
            NOW()
        )
    ");
    $stmt->execute([
        'lead_id'      => $leadId,
        'note'         => mb_substr($note, 0, 255),
        'performed_by'=> $_SESSION['employee_id']
    ]);

    $db->commit();

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

Response::success('Note added successfully');
