<?php
// ─────────────────────────────────────────
//  KAP DSI – Envoi formulaire via Brevo
// ─────────────────────────────────────────

define('BREVO_API_KEY', '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');
define('DEST_EMAIL',    'thierry.dalaigre@kapdsi.fr');
define('DEST_NAME',     'Thierry Dalaigre – KAP DSI');
define('SENDER_EMAIL',  'noreply@kapdsi.fr');
define('SENDER_NAME',   'Formulaire KAP DSI');

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

// ── Diagnostic ─────────────────────────────────────────────────
if (($_GET['diag'] ?? '') === '1') {
    try {
        require_once __DIR__ . '/kap-config.php';
        $pdo = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset='.DB_CHARSET, DB_USER, DB_PASS,
            [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
        $src = $pdo->query("SHOW COLUMNS FROM tickets LIKE 'source'")->fetch(PDO::FETCH_ASSOC);
        echo json_encode(['ok'=>true,'source_enum'=>$src['Type']??'?']);
    } catch (Exception $e) {
        echo json_encode(['ok'=>false,'error'=>$e->getMessage()]);
    }
    exit;
}

// ── Méthode ────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Méthode non autorisée']);
    exit;
}

// ── Anti-spam honeypot ─────────────────────────────────────────
if (!empty($_POST['bot-field'])) {
    echo json_encode(['success' => true]);
    exit;
}

// ── Validation ─────────────────────────────────────────────────
$prenom         = trim($_POST['prenom']         ?? '');
$nom            = trim($_POST['nom']            ?? '');
$email          = trim($_POST['email']          ?? '');
$telephone      = trim($_POST['telephone']      ?? '');
$raison_sociale = trim($_POST['raison_sociale'] ?? '');
$sujet          = trim($_POST['sujet']          ?? '');
$message        = trim($_POST['message']        ?? '');

if (!$prenom || !$nom || !$email || !$message) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Champs obligatoires manquants']);
    exit;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Email invalide']);
    exit;
}

// ── Contenu de l'email ─────────────────────────────────────────
$html = "
<div style='font-family:Arial,sans-serif;max-width:640px;margin:0 auto'>
  <div style='background:#0F2044;padding:24px 28px;border-bottom:3px solid #e05314'>
    <p style='color:#fff;font-size:18px;font-weight:700;margin:0'>KAP DSI — Nouvelle demande de contact</p>
  </div>
  <div style='background:#f5f6f8;padding:28px'>
    <table style='width:100%;border-collapse:collapse'>
      <tr><td style='padding:8px 0;font-weight:700;color:#6b7280;font-size:12px;text-transform:uppercase;width:140px'>Nom</td>
          <td style='padding:8px 0'>{$prenom} {$nom}</td></tr>
      <tr><td style='padding:8px 0;font-weight:700;color:#6b7280;font-size:12px;text-transform:uppercase'>Email</td>
          <td style='padding:8px 0'><a href='mailto:{$email}'>{$email}</a></td></tr>"
. (!empty($telephone) ? "<tr><td style='padding:8px 0;font-weight:700;color:#6b7280;font-size:12px;text-transform:uppercase'>Téléphone</td>
          <td style='padding:8px 0'>{$telephone}</td></tr>" : "")
. (!empty($raison_sociale) ? "<tr><td style='padding:8px 0;font-weight:700;color:#6b7280;font-size:12px;text-transform:uppercase'>Société</td>
          <td style='padding:8px 0'>{$raison_sociale}</td></tr>" : "")
. (!empty($sujet) ? "<tr><td style='padding:8px 0;font-weight:700;color:#6b7280;font-size:12px;text-transform:uppercase'>Sujet</td>
          <td style='padding:8px 0'>{$sujet}</td></tr>" : "")
. "
    </table>
    <div style='margin-top:20px;padding:16px;background:#fff;border-radius:4px;border-left:3px solid #e05314'>
      <p style='margin:0;white-space:pre-line'>" . nl2br(htmlspecialchars($message)) . "</p>
    </div>
  </div>
</div>";

// ── Envoi Brevo ────────────────────────────────────────────────
// Utiliser les paramètres de la base si disponibles, sinon les constantes
try {
    require_once __DIR__ . '/kap-config.php';
    $pdo2 = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset='.DB_CHARSET, DB_USER, DB_PASS,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT]);
    $dynSet = $pdo2->query("SELECT cle,valeur FROM app_settings")->fetchAll(PDO::FETCH_KEY_PAIR);
    $destEmail   = $dynSet['dest_email']  ?? DEST_EMAIL;
    $destName    = $dynSet['dest_name']   ?? DEST_NAME;
    $senderName  = $dynSet['sender_name'] ?? SENDER_NAME;
} catch (Exception $e) {
    $destEmail = DEST_EMAIL; $destName = DEST_NAME; $senderName = SENDER_NAME;
}

$payload = json_encode([
    'sender'      => ['name' => $senderName, 'email' => SENDER_EMAIL],
    'to'          => [['email' => $destEmail, 'name' => $destName]],
    'replyTo'     => ['email' => $email, 'name' => "{$prenom} {$nom}"],
    'subject'     => "Nouvelle demande – {$prenom} {$nom}" . ($raison_sociale ? " ({$raison_sociale})" : ""),
    'htmlContent' => $html,
]);

$ch = curl_init('https://api.brevo.com/v3/smtp/email');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $payload,
    CURLOPT_HTTPHEADER     => [
        'accept: application/json',
        'api-key: ' . BREVO_API_KEY,
        'content-type: application/json',
    ],
    CURLOPT_TIMEOUT => 15,
]);
$response  = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_err  = curl_error($ch);
curl_close($ch);

if ($curl_err) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Erreur réseau : ' . $curl_err]);
    exit;
}

if ($http_code !== 201) {
    http_response_code(500);
    $body = json_decode($response, true);
    echo json_encode(['success' => false, 'error' => $body['message'] ?? 'Erreur Brevo ' . $http_code]);
    exit;
}

// ── Email envoyé avec succès — créer le ticket ─────────────────
$ticketErr = null;
try {
    require_once __DIR__ . '/kap-config.php';
    $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]);
    // Lire les paramètres depuis app_settings (si disponible)
    try {
        $set = $pdo->query("SELECT cle,valeur FROM app_settings")->fetchAll(PDO::FETCH_KEY_PAIR);
    } catch (Exception $e) { $set = []; }

    // Contact connu ?
    $stmt = $pdo->prepare('SELECT id, societe_id FROM contacts WHERE LOWER(email)=?');
    $stmt->execute([strtolower($email)]);
    $contact = $stmt->fetch();

    // UUID
    $b = random_bytes(16);
    $b[6] = chr((ord($b[6]) & 0x0f) | 0x40);
    $b[8] = chr((ord($b[8]) & 0x3f) | 0x80);
    $ticketId = vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($b), 4));

    // Numéro
    $year = (int)date('Y');
    $pdo->prepare("INSERT INTO ticket_seq (annee,seq) VALUES (?,1) ON DUPLICATE KEY UPDATE seq=seq+1")->execute([$year]);
    $seqRow = $pdo->prepare("SELECT seq FROM ticket_seq WHERE annee=?"); $seqRow->execute([$year]);
    $num = sprintf("TK-%d-%03d", $year, (int)$seqRow->fetchColumn());

    // Titre + description
    $titre = $sujet ?: "Demande de contact — {$prenom} {$nom}";
    if (strlen($titre) > 255) $titre = substr($titre, 0, 252) . '…';
    $desc = "Via formulaire kapdsi.fr\n\nNom : {$prenom} {$nom}\nEmail : {$email}"
        . ($raison_sociale ? "\nSociété : {$raison_sociale}" : "")
        . ($telephone      ? "\nTél : {$telephone}"          : "")
        . "\n\nMessage :\n{$message}";

    $contactId = $contact['id']         ?? null;
    $societeId = $contact['societe_id'] ?? null;

    $pdo->prepare("INSERT INTO tickets (id,numero,titre,description,societe_id,contact_id,statut,categorie,source,email_source) VALUES (?,?,?,?,?,?,'nouveau','question','formulaire_contact',?)")
        ->execute([$ticketId, $num, $titre, $desc, $societeId, $contactId, strtolower($email)]);

    // Message initial
    $mb = random_bytes(16); $mb[6]=chr((ord($mb[6])&0x0f)|0x40); $mb[8]=chr((ord($mb[8])&0x3f)|0x80);
    $msgId = vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($mb), 4));
    $pdo->prepare("INSERT INTO ticket_messages (id,ticket_id,auteur_type,auteur_nom,contenu,visible_client) VALUES (?,?,'contact',?,?,1)")
        ->execute([$msgId, $ticketId, trim("{$prenom} {$nom}") ?: $email, $desc]);

} catch (Exception $e) {
    $ticketErr = $e->getMessage();
    error_log('KAP DSI ticket creation error: ' . $e->getMessage());
}

echo json_encode(['success' => true, 'ticket_error' => $ticketErr]);
