<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require __DIR__ . '/PHPMailer/src/Exception.php';
require __DIR__ . '/PHPMailer/src/PHPMailer.php';
require __DIR__ . '/PHPMailer/src/SMTP.php';

// =====================================================
// CONFIGURARE SMTP — înlocuiește cu datele tale
// =====================================================
define('SMTP_HOST',     'ro052.blastwave.ro');  // ex: mail.lapugean.com sau smtp.gmail.com
define('SMTP_USER',     'website@blastwave.ro');        // adresa de trimitere
define('SMTP_PASS',     '$C$UXFl[y&J#ew');         // parola SMTP
define('SMTP_PORT',     465);                        // 587 (TLS) sau 465 (SSL)
define('SMTP_SECURE',   'ssl');                   // 'tls' sau 'ssl'
define('MAIL_TO',       'emilia@divisionpromo.ro');    // destinatar
define('MAIL_TO_NAME',  'Emilia');
// =====================================================

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

$name    = htmlspecialchars(trim($_POST['name']    ?? ''), ENT_QUOTES, 'UTF-8');
$email   = htmlspecialchars(trim($_POST['email']   ?? ''), ENT_QUOTES, 'UTF-8');
$phone   = htmlspecialchars(trim($_POST['phone']   ?? ''), ENT_QUOTES, 'UTF-8');
$message = htmlspecialchars(trim($_POST['message'] ?? ''), ENT_QUOTES, 'UTF-8');
$stars   = intval($_POST['stars'] ?? 0);

if (!$name || !$message) {
    http_response_code(400);
    echo json_encode(['error' => 'Câmpurile sunt incomplete.']);
    exit;
}

$starsLabel = $stars > 0 ? str_repeat('★', $stars) . str_repeat('☆', 5 - $stars) . " ($stars/5)" : '—';

$mail = new PHPMailer(true);

try {
    $mail->isSMTP();
    $mail->Host       = SMTP_HOST;
    $mail->SMTPAuth   = true;
    $mail->Username   = SMTP_USER;
    $mail->Password   = SMTP_PASS;
    $mail->SMTPSecure = SMTP_SECURE === 'ssl' ? PHPMailer::ENCRYPTION_SMTPS : PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = SMTP_PORT;
    $mail->CharSet    = 'UTF-8';
    // Dezactivează verificarea certificatului SSL (necesar pe unele servere shared hosting)
    $mail->SMTPOptions = [
        'ssl' => [
            'verify_peer'       => false,
            'verify_peer_name'  => false,
            'allow_self_signed' => true,
        ]
    ];

    $mail->setFrom(SMTP_USER, 'Cinnamon Beauty Salon');
    $mail->addAddress(MAIL_TO, MAIL_TO_NAME);
    $mail->Subject = "Feedback nou – $starsLabel – $name";
    $mail->isHTML(true);
    $emailRow = $email ? "<p><strong>Email:</strong> $email</p>" : '';
    $phoneRow = $phone ? "<p><strong>Telefon:</strong> $phone</p>" : '';
    $emailAlt = $email ? "\nEmail: $email" : '';
    $phoneAlt = $phone ? "\nTelefon: $phone" : '';

    $mail->Body = "
        <div style='font-family:Arial,sans-serif;max-width:500px'>
            <h2 style='color:#c9a87c'>Feedback nou – Cinnamon Beauty Salon</h2>
            <p><strong>Nume:</strong> $name</p>
            $emailRow
            $phoneRow
            <p><strong>Notă:</strong> $starsLabel</p>
            <hr style='border:none;border-top:1px solid #eee;margin:16px 0'>
            <p><strong>Mesaj:</strong></p>
            <p style='white-space:pre-line'>$message</p>
        </div>
    ";
    $mail->AltBody = "Feedback nou\nNume: $name$emailAlt$phoneAlt\nNotă: $starsLabel\n\nMesaj:\n$message";

    if (isset($_FILES['photo']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
        $allowed = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
        $ftype   = mime_content_type($_FILES['photo']['tmp_name']);
        $fsize   = $_FILES['photo']['size'];

        if (!in_array($ftype, $allowed)) {
            throw new Exception('Tip de fișier nepermis.');
        }
        if ($fsize > 5 * 1024 * 1024) {
            throw new Exception('Poza depășește 5 MB.');
        }

        $mail->addAttachment($_FILES['photo']['tmp_name'], $_FILES['photo']['name']);
    }

    $mail->send();
    echo json_encode(['success' => true]);

} catch (Exception $e) {
    error_log('[send.php] Eroare trimitere mail: ' . $mail->ErrorInfo);
    http_response_code(500);
    echo json_encode(['error' => $mail->ErrorInfo]);
}
