<?php
require_once __DIR__ . '/../../../Models/Database.php';

class CmsController
{
    private $db;

    public function __construct()
    {
        $this->db = Database::getInstance();
    }

    public function sliders()
    {
        $data = $this->db->query("SELECT * FROM app_sliders ORDER BY sort_order ASC")->fetchAll();
        require __DIR__ . '/../../../../views/admin/cms/sliders.php';
    }

    public function snippets()
    {
        $data = $this->db->query("SELECT * FROM app_snippets ORDER BY sort_order ASC")->fetchAll();
        require __DIR__ . '/../../../../views/admin/cms/snippets.php';
    }

    public function storeSnippet()
    {
        $image = $this->handleUpload('image', 'snippets');
        if ($image) {
            $stmt = $this->db->prepare("INSERT INTO app_snippets (title_en, title_ar, sort_order, status, image) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([
                $_POST['title_en'] ?? null,
                $_POST['title_ar'] ?? null,
                $_POST['sort_order'] ?? 0,
                $_POST['status'] ?? 'active',
                $image
            ]);
            header("Location: ?page=snippets&success=Snippet added");
        } else {
            header("Location: ?page=snippets&error=Please upload an image for the snippet");
        }
        exit;
    }

    public function updateSnippet()
    {
        $id = $_POST['id'] ?? 0;
        if ($id) {
            $image = $this->handleUpload('image', 'snippets');

            if ($image) {
                // Update with new image
                $stmt = $this->db->prepare("UPDATE app_snippets SET title_en = ?, title_ar = ?, sort_order = ?, status = ?, image = ? WHERE id = ?");
                $stmt->execute([
                    $_POST['title_en'] ?? null,
                    $_POST['title_ar'] ?? null,
                    $_POST['sort_order'] ?? 0,
                    $_POST['status'] ?? 'active',
                    $image,
                    $id
                ]);
            } else {
                // Update without changing image
                $stmt = $this->db->prepare("UPDATE app_snippets SET title_en = ?, title_ar = ?, sort_order = ?, status = ? WHERE id = ?");
                $stmt->execute([
                    $_POST['title_en'] ?? null,
                    $_POST['title_ar'] ?? null,
                    $_POST['sort_order'] ?? 0,
                    $_POST['status'] ?? 'active',
                    $id
                ]);
            }
            header("Location: ?page=snippets&success=Snippet updated");
        } else {
            header("Location: ?page=snippets&error=Invalid snippet ID");
        }
        exit;
    }

    public function deleteSnippet()
    {
        $id = $_GET['id'] ?? 0;
        $this->db->prepare("DELETE FROM app_snippets WHERE id = ?")->execute([$id]);
        header("Location: ?page=snippets&success=Snippet deleted");
        exit;
    }


    public function faqs()
    {
        $data = $this->db->query("SELECT faqs.*, faq_categories.name_en as category_name_en, faq_categories.name_ar as category_name_ar FROM faqs LEFT JOIN faq_categories ON faqs.category_id = faq_categories.id ORDER BY faq_categories.sort_order ASC, faqs.sort_order ASC")->fetchAll();
        $categories = $this->db->query("SELECT * FROM faq_categories ORDER BY sort_order ASC")->fetchAll();
        require __DIR__ . '/../../../../views/admin/cms/faqs.php';
    }

    public function storeSlider()
    {
        $image = $this->handleUpload('image', 'sliders');
        if ($image) {
            $stmt = $this->db->prepare("INSERT INTO app_sliders (title_en, title_ar, badge_en, badge_ar, subtitle_en, subtitle_ar, button_text_en, button_text_ar, target_type, target_id, target_url, sort_order, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([
                $_POST['title_en'] ?? null,
                $_POST['title_ar'] ?? null,
                $_POST['badge_en'] ?? null,
                $_POST['badge_ar'] ?? null,
                $_POST['subtitle_en'] ?? null,
                $_POST['subtitle_ar'] ?? null,
                $_POST['button_text_en'] ?? null,
                $_POST['button_text_ar'] ?? null,
                $_POST['target_type'] ?? null,
                !empty($_POST['target_id']) ? $_POST['target_id'] : null,
                $_POST['target_url'] ?? null,
                $_POST['sort_order'] ?? 0,
                $_POST['status'] ?? 'active'
            ]);
            header("Location: ?page=sliders&success=Slider added");
        } else {
            header("Location: ?page=sliders&error=Please upload an image for the slider");
        }
        exit;
    }

    public function updateSlider()
    {
        $id = $_POST['id'] ?? 0;
        if ($id) {
            $image = $this->handleUpload('image', 'sliders');

            if ($image) {
                // Update with new image
                $stmt = $this->db->prepare("UPDATE app_sliders SET title_en = ?, title_ar = ?, badge_en = ?, badge_ar = ?, subtitle_en = ?, subtitle_ar = ?, button_text_en = ?, button_text_ar = ?, target_type = ?, target_id = ?, target_url = ?, sort_order = ?, status = ?, image = ? WHERE id = ?");
                $stmt->execute([
                    $_POST['title_en'] ?? null,
                    $_POST['title_ar'] ?? null,
                    $_POST['badge_en'] ?? null,
                    $_POST['badge_ar'] ?? null,
                    $_POST['subtitle_en'] ?? null,
                    $_POST['subtitle_ar'] ?? null,
                    $_POST['button_text_en'] ?? null,
                    $_POST['button_text_ar'] ?? null,
                    $_POST['target_type'] ?? null,
                    !empty($_POST['target_id']) ? $_POST['target_id'] : null,
                    $_POST['target_url'] ?? null,
                    $_POST['sort_order'] ?? 0,
                    $_POST['status'] ?? 'active',
                    $image,
                    $id
                ]);
            } else {
                // Update without changing image
                $stmt = $this->db->prepare("UPDATE app_sliders SET title_en = ?, title_ar = ?, badge_en = ?, badge_ar = ?, subtitle_en = ?, subtitle_ar = ?, button_text_en = ?, button_text_ar = ?, target_type = ?, target_id = ?, target_url = ?, sort_order = ?, status = ? WHERE id = ?");
                $stmt->execute([
                    $_POST['title_en'] ?? null,
                    $_POST['title_ar'] ?? null,
                    $_POST['badge_en'] ?? null,
                    $_POST['badge_ar'] ?? null,
                    $_POST['subtitle_en'] ?? null,
                    $_POST['subtitle_ar'] ?? null,
                    $_POST['button_text_en'] ?? null,
                    $_POST['button_text_ar'] ?? null,
                    $_POST['target_type'] ?? null,
                    !empty($_POST['target_id']) ? $_POST['target_id'] : null,
                    $_POST['target_url'] ?? null,
                    $_POST['sort_order'] ?? 0,
                    $_POST['status'] ?? 'active',
                    $id
                ]);
            }
            header("Location: ?page=sliders&success=Slider updated");
        } else {
            header("Location: ?page=sliders&error=Invalid slider ID");
        }
        exit;
    }

    public function deleteSlider()
    {
        $id = $_GET['id'] ?? 0;
        $this->db->prepare("DELETE FROM app_sliders WHERE id = ?")->execute([$id]);
        header("Location: ?page=sliders&success=Slider deleted");
    }



    public function storeFaq()
    {
        $stmt = $this->db->prepare("INSERT INTO faqs (category_id, question_en, question_ar, answer_en, answer_ar, sort_order, status) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            !empty($_POST['category_id']) ? $_POST['category_id'] : null,
            $_POST['question_en'],
            $_POST['question_ar'] ?? null,
            $_POST['answer_en'],
            $_POST['answer_ar'] ?? null,
            $_POST['sort_order'] ?? 0,
            $_POST['status'] ?? 'active'
        ]);
        header("Location: ?page=faqs&success=FAQ added successfully");
        exit;
    }

    public function updateFaq()
    {
        $id = $_POST['id'] ?? 0;
        if ($id) {
            $stmt = $this->db->prepare("UPDATE faqs SET category_id = ?, question_en = ?, question_ar = ?, answer_en = ?, answer_ar = ?, sort_order = ?, status = ? WHERE id = ?");
            $stmt->execute([
                !empty($_POST['category_id']) ? $_POST['category_id'] : null,
                $_POST['question_en'],
                $_POST['question_ar'] ?? null,
                $_POST['answer_en'],
                $_POST['answer_ar'] ?? null,
                $_POST['sort_order'] ?? 0,
                $_POST['status'] ?? 'active',
                $id
            ]);
            header("Location: ?page=faqs&success=FAQ updated successfully");
        } else {
            header("Location: ?page=faqs&error=Invalid FAQ ID");
        }
        exit;
    }

    public function deleteFaq()
    {
        $id = $_GET['id'] ?? 0;
        $this->db->prepare("DELETE FROM faqs WHERE id = ?")->execute([$id]);
        header("Location: ?page=faqs&success=FAQ deleted successfully");
        exit;
    }

    public function storeFaqCategory()
    {
        $stmt = $this->db->prepare("INSERT INTO faq_categories (name_en, name_ar, description_en, description_ar, icon, sort_order, status) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            $_POST['name_en'],
            $_POST['name_ar'] ?? null,
            $_POST['description_en'] ?? null,
            $_POST['description_ar'] ?? null,
            $_POST['icon'] ?? 'fas fa-question-circle',
            $_POST['sort_order'] ?? 0,
            $_POST['status'] ?? 'active'
        ]);
        header("Location: ?page=faqs&success=Category added successfully");
        exit;
    }

    public function updateFaqCategory()
    {
        $id = $_POST['id'] ?? 0;
        if ($id) {
            $stmt = $this->db->prepare("UPDATE faq_categories SET name_en = ?, name_ar = ?, description_en = ?, description_ar = ?, icon = ?, sort_order = ?, status = ? WHERE id = ?");
            $stmt->execute([
                $_POST['name_en'],
                $_POST['name_ar'] ?? null,
                $_POST['description_en'] ?? null,
                $_POST['description_ar'] ?? null,
                $_POST['icon'] ?? 'fas fa-question-circle',
                $_POST['sort_order'] ?? 0,
                $_POST['status'] ?? 'active',
                $id
            ]);
            header("Location: ?page=faqs&success=Category updated successfully");
        } else {
            header("Location: ?page=faqs&error=Invalid Category ID");
        }
        exit;
    }

    public function deleteFaqCategory()
    {
        $id = $_GET['id'] ?? 0;
        if ($id) {
            // Check if there are active FAQs in this category
            $stmt = $this->db->prepare("SELECT COUNT(*) FROM faqs WHERE category_id = ?");
            $stmt->execute([$id]);
            $count = $stmt->fetchColumn();

            if ($count > 0) {
                header("Location: ?page=faqs&error=Cannot delete category because it contains active FAQs. Please delete or move those FAQs first!");
                exit;
            }

            $this->db->prepare("DELETE FROM faq_categories WHERE id = ?")->execute([$id]);
            header("Location: ?page=faqs&success=Category deleted successfully");
        } else {
            header("Location: ?page=faqs&error=Invalid Category ID");
        }
        exit;
    }

    private function handleUpload($field, $folder)
    {
        if (isset($_FILES[$field]) && $_FILES[$field]['error'] === UPLOAD_ERR_OK) {
            $uploadDir = __DIR__ . '/../../../../public/uploads/cms/' . $folder . '/';
            if (!is_dir($uploadDir))
                mkdir($uploadDir, 0777, true);
            $ext = pathinfo($_FILES[$field]['name'], PATHINFO_EXTENSION);
            $filename = uniqid('cms_') . '.' . $ext;
            if (move_uploaded_file($_FILES[$field]['tmp_name'], $uploadDir . $filename)) {
                return '/public/uploads/cms/' . $folder . '/' . $filename;
            }
        }
        return null;
    }
}
