<?php
if (count(get_included_files()) === 1) { http_response_code(403); exit('Forbidden'); }

if (!isset($_SESSION['user_id'])) {
    header('Location: /login');
    exit;
}

$tenant_id  = (int) $_SESSION['tenant_id'];
$contact_id = (int) ($_GET['contact_id'] ?? 0);
$db = DB::connect();

// Onboarding check
$stmt = $db->prepare("SELECT onboarding_status FROM tenants WHERE id = :t AND deleted_at IS NULL LIMIT 1");
$stmt->execute([':t' => $tenant_id]);
if ($stmt->fetchColumn() !== 'live') {
    header('Location: /onboarding');
    exit;
}

// Contact must belong to this tenant
$stmt = $db->prepare("SELECT id, name, phone, channel, created_at FROM contacts WHERE id = :c AND tenant_id = :t LIMIT 1");
$stmt->execute([':c' => $contact_id, ':t' => $tenant_id]);
$contact = $stmt->fetch();
if (!$contact) {
    http_response_code(404);
    echo '404 Not Found';
    exit;
}

$flash = '';

// POST: edit notes or preferences
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    // Ensure profile row exists
    $db->prepare(
        "INSERT INTO client_profiles (tenant_id, contact_id) VALUES (:t, :c)
         ON DUPLICATE KEY UPDATE updated_at = NOW()"
    )->execute([':t' => $tenant_id, ':c' => $contact_id]);

    if ($action === 'save_all') {
        $phone = mb_substr(trim($_POST['phone'] ?? ''), 0, 40);
        $db->prepare("UPDATE contacts SET phone = :p WHERE id = :c AND tenant_id = :t")
           ->execute([':p' => $phone ?: null, ':c' => $contact_id, ':t' => $tenant_id]);
        $email    = mb_substr(trim($_POST['email'] ?? ''), 0, 160);
        $birthday = trim($_POST['birthday'] ?? '');
        $birthday = preg_match('/^\d{4}-\d{2}-\d{2}$/', $birthday) ? $birthday : null;
        $notes    = mb_substr(trim($_POST['notes'] ?? ''), 0, 4000);

        // Check if this is the first time an email is being saved for this client
        $stmtPrevEmail = $db->prepare("SELECT email FROM client_profiles WHERE tenant_id = :t AND contact_id = :c LIMIT 1");
        $stmtPrevEmail->execute([':t' => $tenant_id, ':c' => $contact_id]);
        $prevEmail = $stmtPrevEmail->fetchColumn();
        $isFirstEmail = $email && !$prevEmail;

        $db->prepare(
            "UPDATE client_profiles SET email = :e, birthday = :b, notes = :n
             WHERE tenant_id = :t AND contact_id = :c"
        )->execute([':e' => $email ?: null, ':b' => $birthday, ':n' => $notes ?: null,
                    ':t' => $tenant_id, ':c' => $contact_id]);

        // Send welcome email on first email capture
        if ($isFirstEmail) {
            try {
                require_once dirname(__DIR__) . '/services/mailer.php';
                $stmtTenant = $db->prepare("SELECT name FROM tenants WHERE id = :t LIMIT 1");
                $stmtTenant->execute([':t' => $tenant_id]);
                $tenantName = $stmtTenant->fetchColumn() ?: 'el negocio';
                Mailer::sendClientWelcome($db, $email, $contact['name'] ?: $email, $tenantName, $tenant_id);
            } catch (Throwable $_me) {
                error_log('[cliente_perfil] mailer error: ' . $_me->getMessage());
            }
        }

        $flash = 'Cambios guardados.';

    } elseif ($action === 'save_pref') {
        $key = mb_substr(trim($_POST['pref_key'] ?? ''), 0, 60);
        $val = mb_substr(trim($_POST['pref_val'] ?? ''), 0, 255);
        if ($key !== '') {
            $stmt = $db->prepare("SELECT preferences FROM client_profiles WHERE tenant_id = :t AND contact_id = :c LIMIT 1");
            $stmt->execute([':t' => $tenant_id, ':c' => $contact_id]);
            $prefs = json_decode($stmt->fetchColumn() ?: '{}', true) ?: [];
            if ($val === '') {
                unset($prefs[$key]);
            } else {
                $prefs[$key] = $val;
            }
            $db->prepare("UPDATE client_profiles SET preferences = :p WHERE tenant_id = :t AND contact_id = :c")
               ->execute([':p' => json_encode($prefs, JSON_UNESCAPED_UNICODE), ':t' => $tenant_id, ':c' => $contact_id]);
        }
        $flash = 'Preferencia guardada.';

    } elseif ($action === 'del_pref') {
        $key = trim($_POST['pref_key'] ?? '');
        if ($key !== '') {
            $stmt = $db->prepare("SELECT preferences FROM client_profiles WHERE tenant_id = :t AND contact_id = :c LIMIT 1");
            $stmt->execute([':t' => $tenant_id, ':c' => $contact_id]);
            $prefs = json_decode($stmt->fetchColumn() ?: '{}', true) ?: [];
            unset($prefs[$key]);
            $db->prepare("UPDATE client_profiles SET preferences = :p WHERE tenant_id = :t AND contact_id = :c")
               ->execute([':p' => json_encode($prefs, JSON_UNESCAPED_UNICODE), ':t' => $tenant_id, ':c' => $contact_id]);
        }
        $flash = 'Preferencia eliminada.';
    }

    header('Location: /clientes/' . $contact_id . ($flash ? '?ok=1' : ''));
    exit;
}

$flash = isset($_GET['ok']) ? 'Cambios guardados.' : '';

// Load fresh profile
$stmt = $db->prepare("SELECT email, birthday, notes, preferences FROM client_profiles WHERE tenant_id = :t AND contact_id = :c LIMIT 1");
$stmt->execute([':t' => $tenant_id, ':c' => $contact_id]);
$profile = $stmt->fetch() ?: ['email' => null, 'birthday' => null, 'notes' => null, 'preferences' => null];
$prefs   = json_decode($profile['preferences'] ?: '{}', true) ?: [];

// Appointments for this contact
$stmt = $db->prepare(
    "SELECT a.id, a.scheduled_at, a.status, s.name AS service_name
     FROM appointments a
     LEFT JOIN services s ON a.service_id = s.id AND s.tenant_id = a.tenant_id
     WHERE a.tenant_id = :t AND a.contact_id = :c
     ORDER BY a.scheduled_at DESC
     LIMIT 50"
);
$stmt->execute([':t' => $tenant_id, ':c' => $contact_id]);
$appointments = $stmt->fetchAll();

require dirname(__DIR__) . '/views/cliente_perfil.php';
