<?php
// Perfil de Cliente renderizado con el mismo UX del perfil de Lead
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(__DIR__))); }
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';
require_once BASE_PATH . '/modules/shared/helpers.php';

if (!function_exists('isLoggedIn')) { function isLoggedIn(){ return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']); } }
if (!isLoggedIn()) { header('Location: ' . get_base_path() . '/index.php?module=auth&action=login'); exit; }

$db = getDB();
$pdo = $db->getConnection();
$current_user_id = (int)($_SESSION['user_id'] ?? 0);
$client_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if ($client_id <= 0) { header('Location: ' . get_base_path() . '/index.php?module=clients&error=invalid_id'); exit; }

// Mapear datos del cliente al esquema esperado por view_content de Leads
$lead = null;
$hasDeskStatus = false;
try { $chk = $pdo->query("SHOW COLUMNS FROM clients LIKE 'desk_status'"); $hasDeskStatus = (bool)$chk->fetch(); } catch (Throwable $__) { $hasDeskStatus = false; }
try {
$sql = "SELECT c.id AS client_id, c.first_name, c.last_name, c.email, c.phone, c.status AS client_status,
                c.created_at, c.updated_at, c.last_seen,
                l.id AS lead_id, l.country, l.source, l.priority, l.status AS lead_status, l.desk_id,
                d.name AS desk_name,
                u.id AS lead_assigned_to, u.username AS lead_assigned_user,
                CONCAT(u.first_name,' ',u.last_name) AS lead_assigned_name,
                c.assigned_to AS client_assigned_to, ucli.username AS client_assigned_user,
                CONCAT(ucli.first_name,' ',ucli.last_name) AS client_assigned_name" . ($hasDeskStatus ? ", c.desk_status AS desk_status" : "") . "
         FROM clients c
         LEFT JOIN leads l ON c.lead_id = l.id
         LEFT JOIN desks d ON c.desk_id = d.id
         LEFT JOIN users u ON l.assigned_to = u.id
         LEFT JOIN users ucli ON c.assigned_to = ucli.id
         WHERE c.id = ? LIMIT 1";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$client_id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($row) {
        $deskStatusVal = isset($row['desk_status']) ? $row['desk_status'] : null;
        $assignedId = $row['client_assigned_to'] ?: $row['lead_assigned_to'];
        $assignedUser = $row['client_assigned_user'] ?: $row['lead_assigned_user'];
        $assignedName = $row['client_assigned_name'] ?: $row['lead_assigned_name'];
        $lead = [
            'id' => ($row['lead_id'] ?: $row['client_id']),
            'first_name' => $row['first_name'],
            'last_name' => $row['last_name'],
            'email' => $row['email'],
            'phone' => $row['phone'],
            'status' => ($deskStatusVal ?: ($row['lead_status'] ?: $row['client_status'])),
            'created_at' => $row['created_at'],
            'updated_at' => $row['updated_at'],
            'last_seen' => $row['last_seen'] ?? $row['updated_at'] ?? $row['created_at'],
            'country' => $row['country'],
            'source' => ($row['source'] ?: 'Cliente'),
            'priority' => ($row['priority'] ?: 'medium'),
            'desk_id' => ($row['desk_id'] ?? 0),
            'desk_name' => ($row['desk_name'] ?? 'Sin desk'),
            'assigned_to' => $assignedId,
            'assigned_user' => $assignedUser,
            'assigned_name' => $assignedName,
        ];
    }
} catch (Exception $e) { $lead = false; }

// Fallback: cargar solo desde clients si los joins no devuelven
if (!$lead) {
    try {
        $stmt2 = $pdo->prepare("SELECT * FROM clients WHERE id = ? LIMIT 1");
        $stmt2->execute([$client_id]);
        $c = $stmt2->fetch(PDO::FETCH_ASSOC);
        if ($c) {
            $statusVal = isset($c['desk_status']) && $c['desk_status'] ? $c['desk_status'] : ($c['status'] ?? 'active');
            $assignedId = (int)($c['assigned_to'] ?? 0);
            $assignedName = null; $assignedUser = null;
            if ($assignedId > 0) {
                try {
                    $stU = $pdo->prepare('SELECT username, CONCAT(first_name, " ", last_name) AS full_name FROM users WHERE id = ?');
                    $stU->execute([$assignedId]);
                    $urow = $stU->fetch(PDO::FETCH_ASSOC);
                    if ($urow) { $assignedUser = $urow['username'] ?? null; $assignedName = $urow['full_name'] ?? null; }
                } catch (Throwable $__) {}
            }
            $lead = [
                'id' => $c['id'],
                'first_name' => $c['first_name'] ?? '',
                'last_name' => $c['last_name'] ?? '',
                'email' => $c['email'] ?? '',
                'phone' => $c['phone'] ?? '',
                'status' => $statusVal,
                'created_at' => $c['created_at'] ?? null,
                'updated_at' => $c['updated_at'] ?? null,
                'last_seen' => $c['last_seen'] ?? ($c['updated_at'] ?? $c['created_at']),
                'country' => '',
                'source' => 'Cliente',
                'priority' => 'medium',
                'desk_id' => $c['desk_id'] ?? 0,
                'desk_name' => '',
                'assigned_to' => ($assignedId ?: null),
                'assigned_user' => $assignedUser,
                'assigned_name' => $assignedName,
            ];
        }
    } catch (Exception $e) { $lead = false; }
}

if (!$lead) { header('Location: ' . get_base_path() . '/index.php?module=clients&error=not_found&id=' . $client_id); exit; }

// Permisos iguales a Leads para máscaras y acciones
if (!function_exists('userHasPermissionByName')) {
    function userHasPermissionByName($pdo, $permName, $userId) {
        if (empty($userId)) return false;
        $stmt = $pdo->prepare("SELECT 1 FROM role_permissions rp INNER JOIN permissions p ON rp.permission_id = p.id INNER JOIN user_roles ur ON rp.role_id = ur.role_id WHERE ur.user_id = ? AND p.name = ? LIMIT 1");
        $stmt->execute([$userId, $permName]);
        return (bool)$stmt->fetchColumn();
    }
}

$canViewEmailFull = userHasPermissionByName($pdo, 'clients.view_email_full', $current_user_id) || userHasPermissionByName($pdo, 'leads.view_email_full', $current_user_id);
$canViewPhoneFull = userHasPermissionByName($pdo, 'clients.view_phone_full', $current_user_id) || userHasPermissionByName($pdo, 'leads.view_phone_full', $current_user_id);

// Layout: usar el mismo contenido del perfil de Lead
$page_title = 'Perfil del Cliente - ' . htmlspecialchars(trim(($lead['first_name'] ?? '') . ' ' . ($lead['last_name'] ?? '')));
$module = 'clients';
$action = 'view';
$current_module = 'clients';
$content_file = BASE_PATH . '/modules/leads/view_content.php';
include BASE_PATH . '/modules/shared/layout.php';
?>
<script>
(function(){
  function notifyList(clientId, status){ try { localStorage.setItem('clients_status_changed', JSON.stringify({client_id: clientId, status: status, t: Date.now()})); } catch(e){} }
  window.updateClientDeskStatus = function(clientId, status){
    if (!clientId || !status) return;
    fetch('<?php echo module_url('clients/api/set_desk_status.php'); ?>', { method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body: 'client_id='+encodeURIComponent(clientId)+'&status='+encodeURIComponent(status) })
      .then(function(r){ return r.json(); })
      .then(function(j){ if (j && j.success){ notifyList(j.client_id, j.status); } })
      .catch(function(){});
  };
  // Auto-hook: si existe un selector de status en la vista, conectarlo
  document.addEventListener('DOMContentLoaded', function(){
    var cid = <?php echo json_encode((int)$client_id); ?>;
    var sel = document.querySelector('#clientStatusSelect, #leadStatusSelect, #lead-status-select, select[name="status"]');
    if (sel){ sel.addEventListener('change', function(){ var val = this.value||''; if (val){ window.updateClientDeskStatus(cid, val); } }); }
  });
})();
</script>
