<?php
// ══════════════════════════════════════════════════════════════════
//  KAP DSI — API CRM
//  Gestion utilisateurs CRM, clients enrichis, activités, missions, pipeline
// ══════════════════════════════════════════════════════════════════

ob_start();
error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('log_errors', '1');

require_once __DIR__ . '/kap-config.php';

header('Content-Type: application/json; charset=utf-8');
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
header('Access-Control-Allow-Origin: ' . $origin);
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Headers: Content-Type, X-KAP-CRM-Token');
header('Access-Control-Allow-Methods: GET, POST, DELETE, OPTIONS');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }

// ── PDO ───────────────────────────────────────────────────────────
function db(): PDO {
    static $pdo = null;
    if ($pdo) return $pdo;
    $pdo = new PDO(
        'mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset='.DB_CHARSET,
        DB_USER, DB_PASS,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false]
    );
    return $pdo;
}

// ── Utils ─────────────────────────────────────────────────────────
function uuid(): string {
    $b = random_bytes(16);
    $b[6] = chr((ord($b[6]) & 0x0f) | 0x40);
    $b[8] = chr((ord($b[8]) & 0x3f) | 0x80);
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($b), 4));
}
function ok(array $d = []): void  { ob_clean(); echo json_encode(['ok' => true] + $d); exit; }
function err(string $m, int $c = 400): void { http_response_code($c); ob_clean(); echo json_encode(['ok' => false, 'error' => $m]); exit; }
function body(): array { return json_decode(file_get_contents('php://input'), true) ?? []; }
function clean(?string $v): string { return strip_tags(trim($v ?? '')); }
function crmToken(): ?string { return $_SERVER['HTTP_X_KAP_CRM_TOKEN'] ?? $_GET['_ct'] ?? null; }

// ── Auth ──────────────────────────────────────────────────────────
function guardCRM(bool $requireSuperAdmin = false): array {
    $token = crmToken();
    if (!$token) err('Non authentifié', 401);
    $stmt = db()->prepare('SELECT s.*, u.id as uid, u.login, u.nom, u.prenom, u.email, u.role, u.actif FROM crm_sessions s JOIN crm_users u ON u.id = s.user_id WHERE s.id = ? AND s.expires_at > NOW()');
    $stmt->execute([$token]);
    $row = $stmt->fetch();
    if (!$row)         err('Session expirée — reconnectez-vous', 401);
    if (!$row['actif']) err('Compte désactivé', 403);
    if ($requireSuperAdmin && $row['role'] !== 'super_admin') err('Droits insuffisants (super admin requis)', 403);
    db()->prepare('UPDATE crm_sessions SET last_seen = NOW(), expires_at = DATE_ADD(NOW(), INTERVAL 8 HOUR) WHERE id = ?')->execute([$token]);
    return $row;
}

// ── Format helpers ────────────────────────────────────────────────
function fmtUser(array $u): array {
    return ['id'=>$u['id'],'login'=>$u['login'],'nom'=>$u['nom'],'prenom'=>$u['prenom'],
            'email'=>$u['email']??'','role'=>$u['role'],'actif'=>(bool)$u['actif'],
            'dateCreation'=>$u['date_creation'],'derniereCnx'=>$u['derniere_cnx']];
}
function fmtActivite(array $a): array {
    return ['id'=>$a['id'],'clientId'=>$a['client_id'],'userId'=>$a['user_id'],
            'userNom'=>($a['user_prenom']??'').' '.($a['user_nom']??''),
            'type'=>$a['type'],'dateActivite'=>$a['date_activite'],
            'dureeMin'=>$a['duree_min'],'resume'=>$a['resume'],'dateCreation'=>$a['date_creation']];
}
function fmtMission(array $m): array {
    return ['id'=>$m['id'],'clientId'=>$m['client_id'],'userId'=>$m['user_id'],
            'intitule'=>$m['intitule'],'description'=>$m['description']??'',
            'dateDebut'=>$m['date_debut'],'dateFin'=>$m['date_fin']??'',
            'joursMois'=>$m['jours_mois'],'tarifJour'=>$m['tarif_jour'],
            'statut'=>$m['statut'],'dateCreation'=>$m['date_creation']];
}
function fmtPipeline(array $p): array {
    return ['id'=>$p['id'],'clientId'=>$p['client_id']??'','userId'=>$p['user_id'],
            'nomProspect'=>$p['nom_prospect'],'societe'=>$p['societe']??'',
            'email'=>$p['email']??'','telephone'=>$p['telephone']??'',
            'stade'=>$p['stade'],'montantEstime'=>$p['montant_estime'],
            'probabilite'=>$p['probabilite'],'source'=>$p['source']??'',
            'notes'=>$p['notes']??'','dateEntree'=>$p['date_entree'],
            'dateClosing'=>$p['date_closing']??'','raisonPerte'=>$p['raison_perte']??'',
            'dateCreation'=>$p['date_creation'],'dateMaj'=>$p['date_maj']??''];
}
function fmtClientCRM(array $c): array {
    return ['id'=>$c['id'],'email'=>$c['email'],'prenom'=>$c['prenom'],'nom'=>$c['nom'],
            'societe'=>$c['societe']??'','telephone'=>$c['telephone']??'','telephone2'=>$c['telephone2']??'',
            'adresse1'=>$c['adresse1']??'','adresse2'=>$c['adresse2']??'',
            'codePostal'=>$c['code_postal']??'','ville'=>$c['ville']??'','pays'=>$c['pays']??'France',
            'statut'=>$c['statut'],'statutRelation'=>$c['statut_relation']??'client_actif',
            'source'=>$c['source']??'','secteur'=>$c['secteur']??'','taille'=>$c['taille']??'',
            'caFourchette'=>$c['ca_fourchette']??'','notes'=>$c['notes']??'',
            'contactNom'=>$c['contact_nom']??'','contactPrenom'=>$c['contact_prenom']??'',
            'contactPoste'=>$c['contact_poste']??'','contactEmail'=>$c['contact_email']??'',
            'contactTel'=>$c['contact_tel']??'',
            'prochainContactDate'=>$c['prochain_contact_date']??'',
            'prochainContactObjet'=>$c['prochain_contact_objet']??'',
            'assignedTo'=>$c['assigned_to']??'',
            'dateCreation'=>$c['date_creation'],'dateMaj'=>$c['date_maj']??''];
}

// ── Routing ───────────────────────────────────────────────────────
$action = $_GET['action'] ?? '';
$method = $_SERVER['REQUEST_METHOD'];

switch ($action) {

// ════════════════════════════════════════════════════════════════
//  AUTH CRM
// ════════════════════════════════════════════════════════════════

case 'ping':
    ok(['php' => PHP_VERSION, 'time' => date('Y-m-d H:i:s')]);

case 'crm_login':
    if ($method !== 'POST') err('Méthode non autorisée', 405);
    $b     = body();
    $login = clean($b['login'] ?? '');
    $pwd   = $b['password'] ?? '';
    if (!$login || !$pwd) err('Identifiant et mot de passe requis');

    $stmt = db()->prepare('SELECT * FROM crm_users WHERE login = ? AND actif = 1');
    $stmt->execute([$login]);
    $user = $stmt->fetch();
    if (!$user || !password_verify($pwd, $user['pwd_hash'])) err('Identifiant ou mot de passe incorrect');

    // Nettoyer les vieilles sessions
    db()->prepare('DELETE FROM crm_sessions WHERE user_id = ? AND expires_at < NOW()')->execute([$user['id']]);

    $token = bin2hex(random_bytes(32));
    db()->prepare('INSERT INTO crm_sessions (id, user_id, ip, user_agent, expires_at) VALUES (?,?,?,?,DATE_ADD(NOW(), INTERVAL 8 HOUR))')
        ->execute([$token, $user['id'], $_SERVER['REMOTE_ADDR'] ?? '', substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 255)]);
    db()->prepare('UPDATE crm_users SET derniere_cnx = NOW() WHERE id = ?')->execute([$user['id']]);

    ok(['token' => $token, 'user' => fmtUser($user)]);

case 'crm_logout':
    $token = crmToken();
    if ($token) db()->prepare('DELETE FROM crm_sessions WHERE id = ?')->execute([$token]);
    ok();

case 'crm_me':
    $u = guardCRM();
    ok(['user' => ['id'=>$u['uid'],'login'=>$u['login'],'nom'=>$u['nom'],
                   'prenom'=>$u['prenom'],'email'=>$u['email'],'role'=>$u['role']]]);

// ════════════════════════════════════════════════════════════════
//  UTILISATEURS CRM (super_admin uniquement)
// ════════════════════════════════════════════════════════════════

case 'crm_users_list':
    guardCRM(true);
    $rows = db()->query('SELECT * FROM crm_users ORDER BY date_creation DESC')->fetchAll();
    ok(['users' => array_map('fmtUser', $rows)]);

case 'crm_user_create':
    guardCRM(true);
    if ($method !== 'POST') err('Méthode non autorisée', 405);
    $b = body();
    if (!clean($b['login']??''))    err('Identifiant obligatoire');
    if (!clean($b['nom']??''))      err('Nom obligatoire');
    if (!clean($b['prenom']??''))   err('Prénom obligatoire');
    if (strlen($b['password']??'') < 8) err('Mot de passe trop court (8 car. min.)');

    $chk = db()->prepare('SELECT id FROM crm_users WHERE login = ?');
    $chk->execute([clean($b['login'])]);
    if ($chk->fetch()) err("L'identifiant existe déjà");

    $id = uuid();
    db()->prepare('INSERT INTO crm_users (id,login,pwd_hash,nom,prenom,email,role) VALUES (?,?,?,?,?,?,?)')
        ->execute([$id, clean($b['login']), password_hash($b['password'], PASSWORD_BCRYPT, ['cost'=>12]),
                   clean($b['nom']), clean($b['prenom']), clean($b['email']??''),
                   in_array($b['role']??'', ['super_admin','standard']) ? $b['role'] : 'standard']);
    $u = db()->prepare('SELECT * FROM crm_users WHERE id = ?');
    $u->execute([$id]);
    ok(['user' => fmtUser($u->fetch())]);

case 'crm_user_update':
    guardCRM(true);
    if ($method !== 'POST') err('Méthode non autorisée', 405);
    $b  = body();
    $id = $b['id'] ?? '';
    $chk = db()->prepare('SELECT * FROM crm_users WHERE id = ?');
    $chk->execute([$id]);
    if (!$chk->fetch()) err('Utilisateur introuvable', 404);

    db()->prepare('UPDATE crm_users SET nom=?,prenom=?,email=?,role=?,actif=? WHERE id=?')
        ->execute([clean($b['nom']??''), clean($b['prenom']??''), clean($b['email']??''),
                   in_array($b['role']??'', ['super_admin','standard']) ? $b['role'] : 'standard',
                   isset($b['actif']) ? (int)(bool)$b['actif'] : 1, $id]);
    if (!empty($b['password']) && strlen($b['password']) >= 8) {
        db()->prepare('UPDATE crm_users SET pwd_hash=? WHERE id=?')
            ->execute([password_hash($b['password'], PASSWORD_BCRYPT, ['cost'=>12]), $id]);
    }
    ok();

case 'crm_user_delete':
    guardCRM(true);
    if ($method !== 'POST') err('Méthode non autorisée', 405);
    $b = body();
    $id = $b['id'] ?? '';
    // Empêcher l'auto-suppression
    $me = guardCRM(true);
    if ($id === $me['uid']) err("Vous ne pouvez pas supprimer votre propre compte");
    db()->prepare('DELETE FROM crm_sessions WHERE user_id = ?')->execute([$id]);
    db()->prepare('DELETE FROM crm_users WHERE id = ?')->execute([$id]);
    ok();

// ════════════════════════════════════════════════════════════════
//  DASHBOARD KPIs
// ════════════════════════════════════════════════════════════════

case 'crm_dashboard':
    guardCRM();
    $today = date('Y-m-d');

    // Clients stats
    $cs = db()->query("SELECT
        COUNT(*) as total,
        SUM(statut_relation='prospect') as prospects,
        SUM(statut_relation='client_actif') as actifs,
        SUM(statut_relation='client_inactif') as inactifs,
        SUM(statut_relation='perdu') as perdus
        FROM clients")->fetch();

    // Pipeline stats
    $ps = db()->query("SELECT
        COUNT(*) as total,
        SUM(stade NOT IN ('gagne','perdu')) as en_cours,
        SUM(stade='gagne') as gagnes,
        SUM(stade='perdu') as perdus,
        SUM(CASE WHEN stade NOT IN ('gagne','perdu') THEN COALESCE(montant_estime*probabilite/100,0) ELSE 0 END) as valeur_ponderee
        FROM pipeline")->fetch();

    // Relances en retard (prochain_contact_date dépassée)
    $relances = db()->query("SELECT c.id, c.prenom, c.nom, c.societe, c.prochain_contact_date, c.prochain_contact_objet
        FROM clients c WHERE c.prochain_contact_date IS NOT NULL AND c.prochain_contact_date <= '$today'
        ORDER BY c.prochain_contact_date ASC LIMIT 10")->fetchAll();

    // Activités récentes (7j)
    $activites = db()->query("SELECT a.*, c.prenom as cprenom, c.nom as cnom, u.prenom as uprenom, u.nom as unom
        FROM activites a
        JOIN clients c ON c.id = a.client_id
        JOIN crm_users u ON u.id = a.user_id
        WHERE a.date_activite >= DATE_SUB(NOW(), INTERVAL 7 DAY)
        ORDER BY a.date_activite DESC LIMIT 8")->fetchAll();

    // Factures en attente
    $factures = db()->query("SELECT COUNT(*) as nb, SUM(montant_ht*(1+tva/100)) as total FROM factures WHERE statut='en attente'")->fetch();

    // Missions en cours
    $missions = db()->query("SELECT COUNT(*) as nb FROM missions WHERE statut='en_cours'")->fetch();

    ok(['stats' => [
        'clients'  => $cs,
        'pipeline' => $ps,
        'factures' => $factures,
        'missions' => $missions,
    ], 'relances' => $relances, 'activitesRecentes' => $activites]);

// ════════════════════════════════════════════════════════════════
//  CLIENTS (enrichis)
// ════════════════════════════════════════════════════════════════

case 'crm_clients':
    guardCRM();
    $q = $_GET['q'] ?? '';
    $statut = $_GET['statut'] ?? '';
    $sql = 'SELECT c.*, (SELECT COUNT(*) FROM factures WHERE client_id=c.id) as nb_factures,
                (SELECT COUNT(*) FROM activites WHERE client_id=c.id) as nb_activites,
                (SELECT COUNT(*) FROM missions WHERE client_id=c.id AND statut="en_cours") as nb_missions,
                u.prenom as assigned_prenom, u.nom as assigned_nom
            FROM clients c LEFT JOIN crm_users u ON u.id = c.assigned_to WHERE 1=1';
    $params = [];
    if ($q) { $sql .= ' AND (c.nom LIKE ? OR c.prenom LIKE ? OR c.societe LIKE ? OR c.email LIKE ?)'; $like = "%$q%"; $params = array_merge($params, [$like,$like,$like,$like]); }
    if ($statut) { $sql .= ' AND c.statut_relation = ?'; $params[] = $statut; }
    $sql .= ' ORDER BY c.date_creation DESC';
    $stmt = db()->prepare($sql);
    $stmt->execute($params);
    $rows = $stmt->fetchAll();
    $clients = array_map(function($c) {
        $r = fmtClientCRM($c);
        $r['nbFactures']  = (int)$c['nb_factures'];
        $r['nbActivites'] = (int)$c['nb_activites'];
        $r['nbMissions']  = (int)$c['nb_missions'];
        $r['assignedNom'] = $c['assigned_prenom'] ? $c['assigned_prenom'].' '.$c['assigned_nom'] : '';
        return $r;
    }, $rows);
    ok(['clients' => $clients]);

case 'crm_client_get':
    guardCRM();
    $id = $_GET['id'] ?? '';
    $stmt = db()->prepare('SELECT * FROM clients WHERE id = ?');
    $stmt->execute([$id]);
    $c = $stmt->fetch();
    if (!$c) err('Client introuvable', 404);
    $r = fmtClientCRM($c);

    // Activités
    $stmt2 = db()->prepare('SELECT a.*, u.prenom as user_prenom, u.nom as user_nom FROM activites a JOIN crm_users u ON u.id=a.user_id WHERE a.client_id=? ORDER BY a.date_activite DESC');
    $stmt2->execute([$id]);
    $r['activites'] = array_map('fmtActivite', $stmt2->fetchAll());

    // Missions
    $stmt3 = db()->prepare('SELECT * FROM missions WHERE client_id=? ORDER BY date_debut DESC');
    $stmt3->execute([$id]);
    $r['missions'] = array_map('fmtMission', $stmt3->fetchAll());

    // Factures
    $stmt4 = db()->prepare('SELECT * FROM factures WHERE client_id=? ORDER BY date_creation DESC');
    $stmt4->execute([$id]);
    $r['factures'] = array_map(function($f) {
        return ['id'=>$f['id'],'numero'=>$f['numero'],'libelle'=>$f['libelle']??'',
                'montantHT'=>(float)$f['montant_ht'],'tva'=>(float)$f['tva'],
                'dateEmission'=>$f['date_emission'],'statut'=>$f['statut'],'hasFile'=>!empty($f['file_name'])];
    }, $stmt4->fetchAll());

    ok(['client' => $r]);

case 'crm_client_update':
    $me = guardCRM();
    if ($method !== 'POST') err('Méthode non autorisée', 405);
    $b  = body();
    $id = $b['id'] ?? '';
    db()->prepare('UPDATE clients SET
        prenom=?,nom=?,societe=?,telephone=?,telephone2=?,adresse1=?,adresse2=?,code_postal=?,ville=?,pays=?,
        statut_relation=?,source=?,secteur=?,taille=?,ca_fourchette=?,notes=?,
        contact_nom=?,contact_prenom=?,contact_poste=?,contact_email=?,contact_tel=?,
        prochain_contact_date=?,prochain_contact_objet=?,assigned_to=?
        WHERE id=?')
    ->execute([
        clean($b['prenom']??''), clean($b['nom']??''), clean($b['societe']??''),
        clean($b['telephone']??''), clean($b['telephone2']??''),
        clean($b['adresse1']??''), clean($b['adresse2']??''),
        clean($b['codePostal']??''), clean($b['ville']??''), clean($b['pays']??'France'),
        in_array($b['statutRelation']??'',['prospect','client_actif','client_inactif','perdu']) ? $b['statutRelation'] : 'client_actif',
        $b['source']??null, clean($b['secteur']??''),
        in_array($b['taille']??'',['TPE','PME','ETI','GE']) ? $b['taille'] : null,
        $b['caFourchette']??null, clean($b['notes']??''),
        clean($b['contactNom']??''), clean($b['contactPrenom']??''), clean($b['contactPoste']??''),
        clean($b['contactEmail']??''), clean($b['contactTel']??''),
        $b['prochainContactDate']??null, clean($b['prochainContactObjet']??''),
        $b['assignedTo']??null,
        $id
    ]);
    ok();

// ════════════════════════════════════════════════════════════════
//  ACTIVITÉS
// ════════════════════════════════════════════════════════════════

case 'activite_add':
    $me = guardCRM();
    if ($method !== 'POST') err('Méthode non autorisée', 405);
    $b = body();
    if (!clean($b['resume']??'')) err('Le résumé est obligatoire');
    $id = uuid();
    db()->prepare('INSERT INTO activites (id,client_id,user_id,type,date_activite,duree_min,resume) VALUES (?,?,?,?,?,?,?)')
        ->execute([$id, $b['clientId']??'', $me['uid'],
                   in_array($b['type']??'',['appel','email','rdv','proposition','relance','note','autre']) ? $b['type'] : 'note',
                   $b['dateActivite'] ?? date('Y-m-d H:i:s'),
                   $b['dureeMin'] ? (int)$b['dureeMin'] : null,
                   clean($b['resume'])]);
    ok(['id' => $id]);

case 'activite_delete':
    $me = guardCRM();
    if ($method !== 'POST') err('Méthode non autorisée', 405);
    $b  = body();
    // Standard peut supprimer ses propres activités, super_admin peut tout supprimer
    $chk = db()->prepare('SELECT user_id FROM activites WHERE id=?');
    $chk->execute([$b['id']??'']);
    $a = $chk->fetch();
    if (!$a) err('Activité introuvable', 404);
    if ($me['role'] !== 'super_admin' && $a['user_id'] !== $me['uid']) err('Vous ne pouvez supprimer que vos propres activités', 403);
    db()->prepare('DELETE FROM activites WHERE id=?')->execute([$b['id']]);
    ok();

// ════════════════════════════════════════════════════════════════
//  MISSIONS
// ════════════════════════════════════════════════════════════════

case 'missions_list':
    guardCRM();
    $clientId = $_GET['client_id'] ?? null;
    if ($clientId) {
        $stmt = db()->prepare('SELECT * FROM missions WHERE client_id=? ORDER BY date_debut DESC');
        $stmt->execute([$clientId]);
    } else {
        $stmt = db()->query('SELECT m.*, c.prenom as cprenom, c.nom as cnom, c.societe FROM missions m JOIN clients c ON c.id=m.client_id ORDER BY m.date_debut DESC');
    }
    ok(['missions' => array_map('fmtMission', $stmt->fetchAll())]);

case 'mission_save':
    $me = guardCRM();
    if ($method !== 'POST') err('Méthode non autorisée', 405);
    $b = body();
    if (!clean($b['intitule']??'')) err("L'intitulé est obligatoire");
    if (!($b['clientId']??''))      err('Le client est obligatoire');
    if (!($b['dateDebut']??''))     err('La date de début est obligatoire');
    $statuts = ['en_cours','pause','terminee','annulee'];
    $st = in_array($b['statut']??'', $statuts) ? $b['statut'] : 'en_cours';
    if (!empty($b['id'])) {
        db()->prepare('UPDATE missions SET intitule=?,description=?,date_debut=?,date_fin=?,jours_mois=?,tarif_jour=?,statut=? WHERE id=?')
            ->execute([clean($b['intitule']), clean($b['description']??''), $b['dateDebut'],
                       $b['dateFin']??null, $b['joursMois']??null, $b['tarifJour']??null, $st, $b['id']]);
        ok();
    } else {
        $id = uuid();
        db()->prepare('INSERT INTO missions (id,client_id,user_id,intitule,description,date_debut,date_fin,jours_mois,tarif_jour,statut) VALUES (?,?,?,?,?,?,?,?,?,?)')
            ->execute([$id, $b['clientId'], $me['uid'], clean($b['intitule']), clean($b['description']??''),
                       $b['dateDebut'], $b['dateFin']??null, $b['joursMois']??null, $b['tarifJour']??null, $st]);
        ok(['id' => $id]);
    }

case 'mission_delete':
    guardCRM(true); // super_admin only
    if ($method !== 'POST') err('Méthode non autorisée', 405);
    $b = body();
    db()->prepare('DELETE FROM missions WHERE id=?')->execute([$b['id']??'']);
    ok();

// ════════════════════════════════════════════════════════════════
//  PIPELINE
// ════════════════════════════════════════════════════════════════

case 'pipeline_list':
    guardCRM();
    $stade = $_GET['stade'] ?? '';
    $sql = 'SELECT * FROM pipeline WHERE 1=1';
    $params = [];
    if ($stade) { $sql .= ' AND stade=?'; $params[] = $stade; }
    $sql .= ' ORDER BY date_creation DESC';
    $stmt = db()->prepare($sql);
    $stmt->execute($params);
    ok(['pipeline' => array_map('fmtPipeline', $stmt->fetchAll())]);

case 'pipeline_save':
    $me = guardCRM();
    if ($method !== 'POST') err('Méthode non autorisée', 405);
    $b = body();
    if (!clean($b['nomProspect']??'')) err('Le nom du prospect est obligatoire');
    $stades = ['decouverte','proposition','negociation','gagne','perdu'];
    $st = in_array($b['stade']??'', $stades) ? $b['stade'] : 'decouverte';
    if (!empty($b['id'])) {
        db()->prepare('UPDATE pipeline SET nom_prospect=?,societe=?,email=?,telephone=?,stade=?,montant_estime=?,probabilite=?,source=?,notes=?,date_entree=?,date_closing=?,raison_perte=? WHERE id=?')
            ->execute([clean($b['nomProspect']), clean($b['societe']??''), clean($b['email']??''),
                       clean($b['telephone']??''), $st,
                       $b['montantEstime']??null, (int)($b['probabilite']??50), $b['source']??null,
                       clean($b['notes']??''), $b['dateEntree']??date('Y-m-d'),
                       $b['dateClosing']??null, clean($b['raisonPerte']??''), $b['id']]);
        ok();
    } else {
        $id = uuid();
        db()->prepare('INSERT INTO pipeline (id,client_id,user_id,nom_prospect,societe,email,telephone,stade,montant_estime,probabilite,source,notes,date_entree,date_closing,raison_perte) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)')
            ->execute([$id, $b['clientId']??null, $me['uid'],
                       clean($b['nomProspect']), clean($b['societe']??''), clean($b['email']??''),
                       clean($b['telephone']??''), $st,
                       $b['montantEstime']??null, (int)($b['probabilite']??50), $b['source']??null,
                       clean($b['notes']??''), $b['dateEntree']??date('Y-m-d'),
                       $b['dateClosing']??null, clean($b['raisonPerte']??'')]);
        ok(['id' => $id]);
    }

case 'pipeline_delete':
    guardCRM();
    if ($method !== 'POST') err('Méthode non autorisée', 405);
    $b  = body();
    $me = guardCRM();
    $chk = db()->prepare('SELECT user_id FROM pipeline WHERE id=?');
    $chk->execute([$b['id']??'']);
    $p = $chk->fetch();
    if (!$p) err('Prospect introuvable', 404);
    if ($me['role'] !== 'super_admin' && $p['user_id'] !== $me['uid']) err('Droits insuffisants', 403);
    db()->prepare('DELETE FROM pipeline WHERE id=?')->execute([$b['id']]);
    ok();

// ════════════════════════════════════════════════════════════════
//  AGENDA (relances + activités à venir)
// ════════════════════════════════════════════════════════════════

case 'agenda':
    guardCRM();
    $today = date('Y-m-d');
    $relances = db()->query("SELECT c.id, c.prenom, c.nom, c.societe, c.prochain_contact_date, c.prochain_contact_objet, c.statut_relation
        FROM clients c WHERE c.prochain_contact_date IS NOT NULL
        ORDER BY c.prochain_contact_date ASC LIMIT 50")->fetchAll();
    ok(['relances' => $relances, 'today' => $today]);

// ════════════════════════════════════════════════════════════════
//  FACTURES (proxy depuis crm-api)
// ════════════════════════════════════════════════════════════════

case 'crm_factures':
    guardCRM();
    $clientId = $_GET['client_id'] ?? null;
    if ($clientId) {
        $stmt = db()->prepare('SELECT f.*, c.prenom, c.nom FROM factures f JOIN clients c ON c.id=f.client_id WHERE f.client_id=? ORDER BY f.date_creation DESC');
        $stmt->execute([$clientId]);
    } else {
        $stmt = db()->query('SELECT f.*, c.prenom, c.nom FROM factures f JOIN clients c ON c.id=f.client_id ORDER BY f.date_creation DESC LIMIT 100');
    }
    $rows = $stmt->fetchAll();
    ok(['factures' => array_map(function($f) {
        return ['id'=>$f['id'],'clientId'=>$f['client_id'],'clientNom'=>$f['prenom'].' '.$f['nom'],
                'numero'=>$f['numero'],'libelle'=>$f['libelle']??'','montantHT'=>(float)$f['montant_ht'],
                'tva'=>(float)$f['tva'],'dateEmission'=>$f['date_emission'],'dateEcheance'=>$f['date_echeance']??'',
                'statut'=>$f['statut'],'hasFile'=>!empty($f['file_name']),'fileName'=>$f['file_name']??''];
    }, $rows)]);

default:
    err('Action inconnue', 404);
}
