<?php
$appName = 'mondialisa';
session_name($appName);
session_start();
require_once "config.inc.php"; // contient $dbh (PDO)

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['tel'])) {

    if (empty($_SESSION['COUNTRY']['alpha2'])) {
        addMsg('info', trad("Veuillez choisir un pays"));
        header('Location: index.php?p=selectcountry');
        exit;
    }

    // --- Vérification captcha ---
    if (!isset($_POST['captcha']) || $_POST['captcha'] != $_SESSION['captcha_result']) {
        addMsg('error', trad("Captcha incorrect"));
        header('Location: index.php?p=newlisting');
        exit;
    }

    try {
        // --- Références ---
        $ref = uniqid("ANN_");
        $user_ref = isset($_SESSION['user']['ref']) ? $_SESSION['user']['ref'] : uniqid("USR_");

        // --- Champs reçus ---
        $titre       = trim($_POST['titre'] ?? '');
        $description = trim($_POST['description'] ?? '');
         $note = trim($_POST['note'] ?? '');
        $categorie   = trim($_POST['cat'] ?? '');
        $ville       = trim($_POST['ville'] ?? '');
        $pays        = trim($_SESSION['COUNTRY']['alpha2']);
        $mdp         = trim($_POST['mdp'] ?? '');
        $nom         = trim($_POST['nom'] ?? 'Utilisateur');
        $tel         = trim($_POST['tel']);
        $email       = trim($_POST['email'] ?? '');
        $type        = trim($_POST['type'] ?? '');
        $prix        = trim($_POST['prix'] ?? '0');
        $statut      = 0;

        // --- Gestion photos V2 ---
        $uploadedPhotos = [];
        $maxFiles = 5;
        $maxBytes = 5 * 1024 * 1024;
        $allowedMimes = ['image/jpeg','image/png','image/gif','image/webp'];

        if (!empty($_FILES['photos']['name'][0])) {
            $files = $_FILES['photos'];
            $total = min(count($files['name']), $maxFiles);

            $targetDir = __DIR__ . "/uploads/annonces/" . $ref . "/";
            if (!is_dir($targetDir)) mkdir($targetDir, 0777, true);

            for ($i = 0; $i < $total; $i++) {
                if ($files['error'][$i] !== UPLOAD_ERR_OK) continue;
                $tmpFile = $files['tmp_name'][$i];
                if (!is_uploaded_file($tmpFile)) continue;
                if (filesize($tmpFile) > $maxBytes) continue;

                $imgInfo = getimagesize($tmpFile);
                if (!$imgInfo || !in_array($imgInfo['mime'], $allowedMimes)) continue;

                switch ($imgInfo['mime']) {
                    case 'image/jpeg': $src = imagecreatefromjpeg($tmpFile); break;
                    case 'image/png':  $src = imagecreatefrompng($tmpFile); break;
                    case 'image/gif':  $src = imagecreatefromgif($tmpFile); break;
                    case 'image/webp': $src = imagecreatefromwebp($tmpFile); break;
                    default: $src = null;
                }
                if (!$src) continue;

                // Resize
                $maxSize = 1200;
                $width  = imagesx($src);
                $height = imagesy($src);
                if ($width > $maxSize || $height > $maxSize) {
                    $ratio = min($maxSize/$width, $maxSize/$height);
                    $newW = intval($width*$ratio);
                    $newH = intval($height*$ratio);
                    $dst = imagecreatetruecolor($newW,$newH);
                    if ($imgInfo['mime']==='image/png'||$imgInfo['mime']==='image/gif') {
                        imagecolortransparent($dst, imagecolorallocatealpha($dst,0,0,0,127));
                        imagealphablending($dst,false);
                        imagesavealpha($dst,true);
                    }
                    imagecopyresampled($dst,$src,0,0,0,0,$newW,$newH,$width,$height);
                    imagedestroy($src);
                    $src = $dst;
                }

                $photoName = uniqid("annonce_") . ".webp";
                $targetFile = $targetDir . $photoName;
                imagewebp($src, $targetFile, 80);
                imagedestroy($src);

                $uploadedPhotos[] = "uploads/annonces/" . $ref . "/" . $photoName;
            }
        }

        $photos_db = implode(",", $uploadedPhotos);

// --- Création utilisateur si non connecté ---
if (!isset($_SESSION['user']) || ($_SESSION['user']['connected'] ?? false) !== true) {

    // Vérifier si utilisateur (tel ou email) existe dans le pays
    $stmt = $dbh->prepare("
        SELECT * FROM mondialisa_users
        WHERE (tel = ? OR email = ?) AND country = ?
        LIMIT 1
    ");
    $stmt->execute([$tel, $email, $pays]);

    if ($stmt->rowCount() > 0) {

        // --- Utilisateur existe déjà ---
        $existingUser = $stmt->fetch(PDO::FETCH_ASSOC);

        // Vérification du mot de passe fourni
        $stmt2 = $dbh->prepare("
            SELECT * FROM mondialisa_users
            WHERE (tel = ? OR email = ?)
            AND pass = PASSWORD(?)
            AND statut = 1
            LIMIT 1
        ");
        $stmt2->execute([$tel, $email, $mdp]);

        if ($stmt2->rowCount() > 0) {

            // --- Connexion réussie ---
            $user = $stmt2->fetch(PDO::FETCH_ASSOC);

              $_SESSION['user'] = $user;          
            $_SESSION['user']['connected'] = true;
            $nom         = trim($_SESSION['user']['firstname']).' '.trim($_SESSION['user']['lastname']);     
            $email       = trim($_SESSION['user']['email']);
            addMsg('success', trad("Connexion réussie. Votre annonce va être enregistrée."));

            // → On continue sans exit pour sauvegarder l’annonce

        } else {
            // Mauvais mot de passe → direction login
            addMsg('error', trad("Mot de passe incorrect. Veuillez vous connecter."));
            header('Location: index.php?p=login');
            exit;
        }

    } else {
        // --- Création de compte ---
        $randompass = !empty($mdp) ? $mdp : uniqid();
        $role = 'user';
        $statut_user = 1;

        $sql = "INSERT INTO mondialisa_users
                (ref, city, country, lastname, tel, email, pass, role, statut)
                VALUES (:ref, :ville, :country, :lastname, :tel, :email, PASSWORD(:pass), :role, :statut)";

        $stmt = $dbh->prepare($sql);
        $stmt->execute([
            ':ref'      => $user_ref,
            ':ville'    => $ville,
            ':country'  => $pays,
            ':lastname' => $nom,
            ':tel'      => $tel,
            ':email'    => $email,
            ':pass'     => $randompass,
            ':role'     => $role,
            ':statut'   => $statut_user,
        ]);

        addMsg('info', trad("Compte utilisateur créé avec succès") . "<br>"
            . $tel . '/' . $randompass . "<br>"
            . trad("Copiez ces informations de connexion"),null,0);

        // Connexion automatique après création
        $_SESSION['user'] = [
            'connected' => true,
            'ref'      => $user_ref,
            'lastname' => $nom,
            'tel'      => $tel,
            'email'    => $email,
            'country'  => $pays,
            'role'     => $role
        ];
    }
}


        // --- Insertion annonce ---
        $sql = "INSERT INTO mondialisa_annonces 
                (ref, user_ref, titre, description, note, categorie, ville, pays, nom, tel, email, type, photo, prix, statut)
                VALUES (:ref, :user_ref, :titre, :description, :note, :categorie, :ville, :pays, :nom, :tel, :email, :type, :photo, :prix, :statut)";

        $stmt = $dbh->prepare($sql);
        $stmt->bindParam(':ref', $ref);
        $stmt->bindParam(':user_ref', $user_ref);
        $stmt->bindParam(':titre', $titre);
        $stmt->bindParam(':description', $description);
             $stmt->bindParam(':note', $note);
        $stmt->bindParam(':categorie', $categorie);
        $stmt->bindParam(':ville', $ville);
        $stmt->bindParam(':pays', $pays);
        $stmt->bindParam(':nom', $nom);
        $stmt->bindParam(':tel', $tel);
        $stmt->bindParam(':email', $email);
        $stmt->bindParam(':type', $type);
        $stmt->bindParam(':photo', $photos_db);
        $stmt->bindParam(':prix', $prix);
        $stmt->bindParam(':statut', $statut, PDO::PARAM_INT);
        $stmt->execute();

        addMsg('success', trad("Listing saved successfully"));
        header('Location: index.php?p=mes_annonces');
        exit;

    } catch (PDOException $e) {
        catcherror($e, trad("Listing not saved"));
        header('Location: index.php?error=db');
        exit;
    }
} else {
    addMsg('info', trad("error request"));
    header('Location: index.php?save=error');
    exit;
}
