<?php
require_once "../../config/db.php";
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id'] ?? null;
    $name = trim($_POST['product_name']);
    $category_id = $_POST['category_id'];
    $description = $_POST['description'];
    $challenges = trim($_POST['challenges'] ?? '');
    $solutions = trim($_POST['solutions'] ?? '');
    $result = trim($_POST['result'] ?? '');

    // ✅ Dynamic Descriptions (new)
    $dynamic_description_1 = trim($_POST['dynamic_description_1'] ?? '');
    $dynamic_description_2 = trim($_POST['dynamic_description_2'] ?? '');

    // ✅ Testimonial
    $testimonial = [
        'client_name' => trim($_POST['testimonial_client_name'] ?? ''),
        'designation' => trim($_POST['testimonial_designation'] ?? ''),
        'message' => trim($_POST['testimonial_message'] ?? '')
    ];
    $testimonial_json = json_encode($testimonial, JSON_UNESCAPED_UNICODE);

    $seo_title = $_POST['seo_title'];
    $meta_keywords = $_POST['meta_keywords'];
    $meta_description = $_POST['meta_description'];
    $featured_product = isset($_POST['featured_product']) ? 1 : 0;

    $primarykw = $name;

    // ✅ Keep placeholders in DB (no replacement before saving)
    function slugify($text)
    {
        $text = trim($text ?? '');
        if ($text === '') return '';
        $arabicMap = [
            'أ'=>'a','إ'=>'i','آ'=>'a','ؤ'=>'u','ئ'=>'i','ء'=>'a','ا'=>'a','ب'=>'b','ت'=>'t','ث'=>'th','ج'=>'j','ح'=>'h','خ'=>'kh',
            'د'=>'d','ذ'=>'dh','ر'=>'r','ز'=>'z','س'=>'s','ش'=>'sh','ص'=>'s','ض'=>'d','ط'=>'t','ظ'=>'z','ع'=>'a','غ'=>'gh','ف'=>'f','ق'=>'q',
            'ك'=>'k','ل'=>'l','م'=>'m','ن'=>'n','ه'=>'h','و'=>'w','ي'=>'y','ى'=>'a','ة'=>'h','ﻻ'=>'la','ﻷ'=>'la','ﻹ'=>'la','ﻵ'=>'la'
        ];
        $text = strtr($text, $arabicMap);
        $text = preg_replace('~[^\pL\d]+~u', '-', $text);
        if (function_exists('iconv')) {
            $converted = @iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $text);
            if ($converted !== false) $text = $converted;
        }
        $text = preg_replace('~[^-\w]+~', '', $text);
        $text = trim($text, '-');
        $text = preg_replace('~-+~', '-', $text);
        return strtolower($text) ?: 'unknown';
    }

    $slug = slugify($name);

    // ✅ Handle single image upload
    $imageName = null;
    if (!empty($_FILES['product_image']['name'])) {
        $uploadDir = "../uploads/";
        if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
        $ext = pathinfo($_FILES['product_image']['name'], PATHINFO_EXTENSION);
        $imageName = uniqid() . "." . $ext;
        move_uploaded_file($_FILES['product_image']['tmp_name'], $uploadDir . $imageName);
    }

    // ✅ Insert or Update
    if ($id) {
        if ($imageName) {
            $sql = "UPDATE products 
                    SET name=?, category_id=?, image=?, description=?, challenges=?, solutions=?, result=?, 
                        dynamic_description_1=?, dynamic_description_2=?, testimonial=?, seo_title=?, 
                        meta_keywords=?, meta_description=?, slug=?, featured_product=? 
                    WHERE id=?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$name, $category_id, $imageName, $description, $challenges, $solutions, $result,
                            $dynamic_description_1, $dynamic_description_2, $testimonial_json, $seo_title, 
                            $meta_keywords, $meta_description, $slug, $featured_product, $id]);
        } else {
            $sql = "UPDATE products 
                    SET name=?, category_id=?, description=?, challenges=?, solutions=?, result=?, 
                        dynamic_description_1=?, dynamic_description_2=?, testimonial=?, seo_title=?, 
                        meta_keywords=?, meta_description=?, slug=?, featured_product=? 
                    WHERE id=?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$name, $category_id, $description, $challenges, $solutions, $result,
                            $dynamic_description_1, $dynamic_description_2, $testimonial_json, $seo_title, 
                            $meta_keywords, $meta_description, $slug, $featured_product, $id]);
        }
    } else {
        $sql = "INSERT INTO products 
                (name, category_id, image, description, challenges, solutions, result, 
                 dynamic_description_1, dynamic_description_2, testimonial, seo_title, 
                 meta_keywords, meta_description, slug, featured_product) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$name, $category_id, $imageName, $description, $challenges, $solutions, $result,
                        $dynamic_description_1, $dynamic_description_2, $testimonial_json, $seo_title, 
                        $meta_keywords, $meta_description, $slug, $featured_product]);
        $id = $pdo->lastInsertId();
    }

    // ✅ Save Tags
    if (!empty($_POST['product_tags'])) {
        $tags = array_map('trim', explode(',', $_POST['product_tags']));
        $pdo->prepare("DELETE FROM product_tags WHERE product_id = ?")->execute([$id]);
        foreach ($tags as $tag) {
            if (!$tag) continue;
            $tag_slug = slugify($tag);
            $stmt = $pdo->prepare("INSERT INTO product_tags (product_id, tag_name, slug) VALUES (?, ?, ?)");
            $stmt->execute([$id, $tag, $tag_slug]);
        }
    }

    // ✅ Dynamic Page Generation
    $generatedPages = [];

    if (isset($_POST['create_pages']) && $_POST['create_pages'] === "yes") {
        if (!empty($_POST['secondary_keyword']) && !empty($_POST['locations'])) {
            $primarykw = $name;
            $selectedSubcats = $_POST['secondary_keyword'];
            $selectedLocations = $_POST['locations'];

            foreach ($selectedSubcats as $sub) {
                foreach ($selectedLocations as $loc) {
                    $title = "$primarykw $sub in $loc";
                    $page_slug = slugify($primarykw . "-" . $sub . "-" . $loc);

                    $stmt = $pdo->prepare("SELECT COUNT(*) FROM product_page WHERE slug = ? AND product_id = ?");
                    $stmt->execute([$page_slug, $id]);

                    if ($stmt->fetchColumn() == 0) {
                        $stmt = $pdo->prepare("
                            INSERT INTO product_page 
                            (product_id, title, slug, main_title, main_description, meta_title, meta_description, meta_keywords) 
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                        ");

                        // ✅ Replace variables dynamically when generating pages
                        $finalDescription = str_replace(
                            ['$loc', '$seckw', '$primarykw'],
                            [$loc, $sub, $primarykw],
                            $description
                        );

                        $finalDynamic1 = str_replace(
                            ['$loc', '$seckw', '$primarykw'],
                            [$loc, $sub, $primarykw],
                            $dynamic_description_1
                        );

                        $finalDynamic2 = str_replace(
                            ['$loc', '$seckw', '$primarykw'],
                            [$loc, $sub, $primarykw],
                            $dynamic_description_2
                        );

                        $userMetaDesc = trim($_POST['meta_description']);
                        $userMetaKeys = trim($_POST['meta_keywords']);

                        $autoMetaDesc = "$title.";
                        $autoMetaKeys = strtolower($primarykw) . ", " . strtolower($sub) . ", " . strtolower($loc);

                        $finalMetaDesc = $userMetaDesc
                            ? $userMetaDesc . ". " . $autoMetaDesc
                            : $autoMetaDesc;

                        $finalMetaKeys = $userMetaKeys
                            ? $userMetaKeys . ", " . $autoMetaKeys
                            : $autoMetaKeys;

                        $stmt->execute([
                            $id,
                            $title,
                            $page_slug,
                            $title,
                            $finalDescription,
                            $title,
                            $finalMetaDesc,
                            $finalMetaKeys
                        ]);
                    }

                    $generatedPages[] = [
                        "title" => $title,
                        "slug"  => $page_slug
                    ];
                }
            }
        }
    }

    $_SESSION['generatedPages'] = $generatedPages;
    header("Location: product.php?id=" . $id);
    exit;
}
?>
