<?php
// Configuration
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

// Désactiver l'affichage des erreurs dans la sortie
ini_set('display_errors', 0);
error_reporting(E_ALL);

// Votre adresse email
$to = "yessinegargouri07@gmail.com";
$subject = "Nouvelle candidature - Programme Ingénieurs IT Tunisie-France";

// Vérifier que c'est une requête POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Méthode non autorisée']);
    exit;
}

// Récupérer les données du formulaire
$email = filter_var($_POST['email'] ?? '', FILTER_SANITIZE_EMAIL);
$fullName = htmlspecialchars($_POST['fullName'] ?? '', ENT_QUOTES, 'UTF-8');
$phone = htmlspecialchars($_POST['phone'] ?? '', ENT_QUOTES, 'UTF-8');
$availability = htmlspecialchars($_POST['availability'] ?? '', ENT_QUOTES, 'UTF-8');
$educationLevel = htmlspecialchars($_POST['educationLevel'] ?? '', ENT_QUOTES, 'UTF-8');
$experienceYears = htmlspecialchars($_POST['experienceYears'] ?? '', ENT_QUOTES, 'UTF-8');
$speciality = htmlspecialchars($_POST['speciality'] ?? '', ENT_QUOTES, 'UTF-8');
$careerWish = htmlspecialchars($_POST['careerWish'] ?? '', ENT_QUOTES, 'UTF-8');
$expectations = htmlspecialchars($_POST['expectations'] ?? '', ENT_QUOTES, 'UTF-8');
$rgpdConsent = isset($_POST['rgpdConsent']) ? 'Oui' : 'Non';

// Validation
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Email invalide']);
    exit;
}

if (empty($fullName) || empty($phone) || empty($availability) || empty($educationLevel) || 
    empty($experienceYears) || empty($speciality) || empty($careerWish) || empty($expectations)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Tous les champs sont obligatoires']);
    exit;
}

// Gestion du fichier CV
$cvAttachment = null;
$cvFileName = '';
if (isset($_FILES['cv']) && $_FILES['cv']['error'] === UPLOAD_ERR_OK) {
    $allowedTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
    $maxSize = 10 * 1024 * 1024; // 10 MB
    
    if (!in_array($_FILES['cv']['type'], $allowedTypes)) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Format de fichier non accepté. Utilisez PDF ou DOCX.']);
        exit;
    }
    
    if ($_FILES['cv']['size'] > $maxSize) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Le fichier est trop volumineux (max 10 MB)']);
        exit;
    }
    
    $cvFileName = $_FILES['cv']['name'];
    $cvAttachment = file_get_contents($_FILES['cv']['tmp_name']);
}

// Traduire les valeurs en français
$educationLabels = [
    'licence' => 'Licence',
    'ingenieur' => 'Ingénieur',
    'master_doctorat' => 'Master / Doctorat'
];

$specialityLabels = [
    'devops' => 'DevOps',
    'cloud' => 'Cloud',
    'data_ia' => 'Data / IA',
    'cybersecurite' => 'Cybersécurité',
    'developpement_logiciel' => 'Développement logiciel'
];

$careerLabels = [
    'france' => 'Travailler en France',
    'remote' => 'Collaborer à distance avec des entreprises françaises'
];

$educationText = $educationLabels[$educationLevel] ?? $educationLevel;
$specialityText = $specialityLabels[$speciality] ?? $speciality;
$careerText = $careerLabels[$careerWish] ?? $careerWish;

// Créer le contenu de l'email en HTML
$message = "
<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
        .container { max-width: 600px; margin: 0 auto; padding: 20px; }
        .header { background: linear-gradient(135deg, #8a54ff, #548aff); color: white; padding: 20px; border-radius: 8px 8px 0 0; }
        .section { background: #f9f9f9; padding: 15px; margin: 10px 0; border-left: 4px solid #8a54ff; }
        .section-title { font-weight: bold; color: #8a54ff; margin-bottom: 10px; }
        .field { margin: 8px 0; }
        .label { font-weight: 600; color: #555; }
        .value { color: #333; }
    </style>
</head>
<body>
    <div class='container'>
        <div class='header'>
            <h2>Nouvelle Candidature - Programme Ingénieurs IT</h2>
            <p>Tunisie–France</p>
        </div>
        
        <div class='section'>
            <div class='section-title'>📋 Informations Personnelles</div>
            <div class='field'><span class='label'>Nom complet:</span> <span class='value'>{$fullName}</span></div>
            <div class='field'><span class='label'>Email:</span> <span class='value'>{$email}</span></div>
            <div class='field'><span class='label'>Téléphone / WhatsApp:</span> <span class='value'>{$phone}</span></div>
            <div class='field'><span class='label'>Disponibilité:</span> <span class='value'>{$availability}</span></div>
        </div>
        
        <div class='section'>
            <div class='section-title'>🎓 Parcours Académique & Professionnel</div>
            <div class='field'><span class='label'>Niveau d'études:</span> <span class='value'>{$educationText}</span></div>
            <div class='field'><span class='label'>Années d'expérience:</span> <span class='value'>{$experienceYears} ans</span></div>
            <div class='field'><span class='label'>Spécialité principale:</span> <span class='value'>{$specialityText}</span></div>
            <div class='field'><span class='label'>Souhait professionnel:</span> <span class='value'>{$careerText}</span></div>
        </div>
        
        <div class='section'>
            <div class='section-title'>💡 Motivation & Attentes</div>
            <div class='field'>
                <div class='label'>Attentes de la formation:</div>
                <div class='value' style='margin-top: 8px; white-space: pre-wrap;'>{$expectations}</div>
            </div>
        </div>
        
        <div class='section'>
            <div class='section-title'>✅ Consentement RGPD</div>
            <div class='field'><span class='value'>{$rgpdConsent}</span></div>
        </div>
        
        <div style='margin-top: 20px; padding: 15px; background: #e8f5e9; border-radius: 8px;'>
            <p style='margin: 0;'><strong>📎 CV joint:</strong> {$cvFileName}</p>
        </div>
    </div>
</body>
</html>
";

// Configuration de l'email avec pièce jointe
$boundary = md5(time());

$headers = "From: Programme IT <noreply@LinQini.com>\r\n";
$headers .= "Reply-To: {$email}\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"{$boundary}\"\r\n";

$emailBody = "--{$boundary}\r\n";
$emailBody .= "Content-Type: text/html; charset=UTF-8\r\n";
$emailBody .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$emailBody .= $message . "\r\n";

// Ajouter la pièce jointe si elle existe
if ($cvAttachment && $cvFileName) {
    $cvEncoded = chunk_split(base64_encode($cvAttachment));
    $emailBody .= "--{$boundary}\r\n";
    $emailBody .= "Content-Type: application/octet-stream; name=\"{$cvFileName}\"\r\n";
    $emailBody .= "Content-Transfer-Encoding: base64\r\n";
    $emailBody .= "Content-Disposition: attachment; filename=\"{$cvFileName}\"\r\n\r\n";
    $emailBody .= $cvEncoded . "\r\n";
}

$emailBody .= "--{$boundary}--";

// Envoyer l'email
$mailSent = @mail($to, $subject, $emailBody, $headers);

// Toujours retourner une réponse JSON propre
if ($mailSent) {
    http_response_code(200);
    echo json_encode([
        'success' => true,
        'message' => 'Votre candidature a été envoyée avec succès ! Nous vous contacterons bientôt.',
        'debug' => [
            'to' => $to,
            'subject' => $subject,
            'hasCV' => !empty($cvFileName)
        ]
    ], JSON_UNESCAPED_UNICODE);
} else {
    http_response_code(200); // Garder 200 pour que Angular puisse lire la réponse
    echo json_encode([
        'success' => false,
        'message' => 'Erreur lors de l\'envoi de l\'email. Veuillez réessayer ou nous contacter directement.',
        'debug' => [
            'mail_function_exists' => function_exists('mail'),
            'error' => error_get_last()
        ]
    ], JSON_UNESCAPED_UNICODE);
}

// S'assurer qu'aucun autre contenu n'est envoyé
exit;
?>
