<?php
class ProductsController extends Controller {

    public function index() {

        $productModel = $this->model('Product');
        $categoryModel = $this->model('Category');

        if (session_status() == PHP_SESSION_NONE) session_start();

        $uploadPath = 'assets/images/products/';
        $galleryPath = 'assets/images/products/gallery/';

        if (!is_dir($galleryPath)) mkdir($galleryPath, 0777, true);

        // =========================
        //   ADD PRODUCT
        // =========================
        if (isset($_POST['add'])) {

            $imageName = null;

            if (!empty($_FILES['pro_image']['name'])) {

                $ext = strtolower(pathinfo($_FILES['pro_image']['name'], PATHINFO_EXTENSION));

                if (!in_array($ext, ['png','jpg','jpeg','webp'])) {
                    $_SESSION['message'] = "Invalid image format!";
                    header('Location: '.BASE_URL.'/products');
                    exit;
                }

                $imageName = time().'_'.$_FILES['pro_image']['name'];
                move_uploaded_file($_FILES['pro_image']['tmp_name'], $uploadPath.$imageName);
            }

            $productId = $productModel->add([
                'pro_title' => $_POST['pro_title'],
                'pro_material' => $_POST['pro_material'],
                'category_id' => $_POST['category_id'],
                'sub_category_id' => $_POST['sub_category_id'] ?? null,
                'price' => $_POST['price'] ?? 0,
                'sale_price' => $_POST['sale_price'] ?? 0,
                'highlight' => $_POST['highlight'] ?? '',
                'description' => $_POST['description'] ?? '',
                'benefits' => $_POST['benefits'] ?? '',
                'how_to_use' => $_POST['how_to_use'] ?? '',
                'ideal_for' => $_POST['ideal_for'] ?? '',
                'care' => $_POST['care'] ?? '',
                'special_instruction' => $_POST['special_instruction'] ?? '',
                'short_description' => $_POST['short_description'] ?? '',
                'pro_image' => $imageName
            ]);

            // GALLERY
            if (!empty($_FILES['gallery_images']['name'][0])) {
                $images = [];

                foreach ($_FILES['gallery_images']['tmp_name'] as $key => $tmp) {
                    $file = time().'_'.$_FILES['gallery_images']['name'][$key];
                    move_uploaded_file($tmp, $galleryPath.$file);
                    $images[] = $file;
                }

                $productModel->addImages($productId, $images);
            }

            $_SESSION['message'] = "Product Added Successfully!";
            header('Location: '.BASE_URL.'/products');
            exit;
        }

        // =========================
        // 🟡 EDIT PRODUCT
        // =========================
        if (isset($_POST['edit'])) {

            $id = $_POST['id'];
            $imageName = $_POST['old_image'];

            if (!empty($_FILES['pro_image']['name'])) {

                if (!empty($imageName) && file_exists($uploadPath.$imageName)) {
                    unlink($uploadPath.$imageName);
                }

                $imageName = time().'_'.$_FILES['pro_image']['name'];
                move_uploaded_file($_FILES['pro_image']['tmp_name'], $uploadPath.$imageName);
            }

            $productModel->update($id, [
                'pro_title' => $_POST['pro_title'],
                'pro_material' => $_POST['pro_material'],
                'category_id' => $_POST['category_id'],
                'sub_category_id' => $_POST['sub_category_id'] ?? null,
                'price' => $_POST['price'] ?? 0,
                'sale_price' => $_POST['sale_price'] ?? 0,
                'highlight' => $_POST['highlight'] ?? '',
                'description' => $_POST['description'] ?? '',
                'benefits' => $_POST['benefits'] ?? '',
                'how_to_use' => $_POST['how_to_use'] ?? '',
                'ideal_for' => $_POST['ideal_for'] ?? '',
                'care' => $_POST['care'] ?? '',
                'special_instruction' => $_POST['special_instruction'] ?? '',
                'short_description' => $_POST['short_description'] ?? '',
                'pro_image' => $imageName
            ]);

            // NEW GALLERY ADD
            if (!empty($_FILES['gallery_images']['name'][0])) {
                $images = [];

                foreach ($_FILES['gallery_images']['tmp_name'] as $key => $tmp) {
                    $file = time().'_'.$_FILES['gallery_images']['name'][$key];
                    move_uploaded_file($tmp, $galleryPath.$file);
                    $images[] = $file;
                }

                $productModel->addImages($id, $images);
            }

            $_SESSION['message'] = "Product Updated Successfully!";
            header('Location: '.BASE_URL.'/products');
            exit;
        }

        // ================= CLONE PRODUCT =================
if(isset($_GET['clone'])){

    $id = $_GET['clone'];

    // old product fetch
    $old = $productModel->get($id);

    if($old){

        // 🔥 IMAGE COPY
        $newImage = null;
        if(!empty($old['pro_image'])){
            $oldPath = $uploadPath.$old['pro_image'];
            if(file_exists($oldPath)){
                $newImage = time().'_'.$old['pro_image'];
                copy($oldPath, $uploadPath.$newImage);
            }
        }

        // 🔥 INSERT NEW PRODUCT
        $newProductId = $productModel->add([
            'pro_title' => $old['pro_title'].' Copy',
            'pro_material' => $old['pro_material'],
            'category_id' => $old['category_id'],
            'sub_category_id' => $old['sub_category_id'],
            'price' => $old['price'],
            'sale_price' => $old['sale_price'],
            'highlight' => $old['highlight'],
            'description' => $old['description'],
            'benefits' => $old['benefits'],
            'how_to_use' => $old['how_to_use'],
            'ideal_for' => $old['ideal_for'],
            'care' => $old['care'],
            'special_instruction' => $old['special_instruction'],
            'short_description' => $old['short_description'],
            'pro_image' => $newImage
        ]);

        // 🔥 GALLERY COPY
        $images = $productModel->getImages($id);
        $newImages = [];

        foreach($images as $img){
            $oldImgPath = $galleryPath.$img['image_name'];

            if(file_exists($oldImgPath)){
                $newName = time().'_'.$img['image_name'];
                copy($oldImgPath, $galleryPath.$newName);
                $newImages[] = $newName;
            }
        }

        if(!empty($newImages)){
            $productModel->addImages($newProductId, $newImages);
        }

        $_SESSION['message'] = "Product Cloned Successfully!";
    }

    header('Location: '.BASE_URL.'/products');
    exit;
}

        // =========================
        //  DELETE GALLERY IMAGE
        // =========================
        if (isset($_GET['delete_image'])) {

            $imgId = $_GET['delete_image'];

            $conn = $productModel->getConnection();

            $stmt = $conn->prepare("SELECT * FROM product_images WHERE id = :id");
            $stmt->execute([':id'=>$imgId]);

            $img = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($img && file_exists($galleryPath.$img['image_name'])) {
                unlink($galleryPath.$img['image_name']);
            }

            $productModel->deleteImage($imgId);

            $_SESSION['message'] = "Gallery Image Deleted!";
            header('Location: '.BASE_URL.'/products?edit='.$_GET['edit']);
            exit;
        }

        // =========================
        // DELETE PRODUCT
        // =========================
        if (isset($_GET['delete'])) {

            $id = $_GET['delete'];

            $product = $productModel->get($id);

            if ($product && !empty($product['pro_image']) && file_exists($uploadPath.$product['pro_image'])) {
                unlink($uploadPath.$product['pro_image']);
            }

            $galleryImages = $productModel->getImages($id);

            foreach ($galleryImages as $img) {
                if (file_exists($galleryPath.$img['image_name'])) {
                    unlink($galleryPath.$img['image_name']);
                }
            }

            $productModel->deleteAllImagesByProduct($id);
            $productModel->delete($id);

            $_SESSION['message'] = "Product Deleted Successfully!";
            header('Location: '.BASE_URL.'/products');
            exit;
        }

        // =========================
        //  FETCH DATA
        // =========================
        $data['products'] = $productModel->getAll();
        $data['categories'] = $categoryModel->getAll();
        $data['title'] = "Products";

        $this->view('templates/header', $data);
        $this->view('products', $data);
        $this->view('templates/footer', $data);
    }
}