<?php

namespace App\Controllers;

use App\Models\SettingModel;
use App\Models\PageModel;
use App\Models\ProductModel;
use App\Models\CategoryModel;

class Home extends BaseController
{
    private function getSettings()
    {
        $settingModel = new SettingModel();
        $allSettings = $settingModel->findAll();
        $settings = [];
        foreach ($allSettings as $s) {
            $settings[$s['key_name']] = $s['value'];
        }
        return $settings;
    }

    public function index()
    {
        $data['settings'] = $this->getSettings();
        
        $bannerModel = new \App\Models\BannerModel();
        $data['banners'] = $bannerModel->where('status', 1)->orderBy('sort_order', 'ASC')->findAll();

        $pageModel = new PageModel();
        $data['page'] = $pageModel->where('slug', 'home')->first();
        
        $productModel = new ProductModel();
        $data['featured_products'] = $productModel->where('is_featured', 1)->where('status', 1)->findAll(4);
        
        $data['meta_title'] = $data['page']['meta_title'] ?? null;
        $data['meta_description'] = $data['page']['meta_description'] ?? null;
        
        return view('front/home', $data);
    }

    public function about()
    {
        $data['settings'] = $this->getSettings();
        $pageModel = new PageModel();
        $data['page'] = $pageModel->where('slug', 'about')->first();
        
        $data['meta_title'] = $data['page']['meta_title'] ?? null;
        $data['meta_description'] = $data['page']['meta_description'] ?? null;
        
        return view('front/about', $data);
    }

    public function products($categorySlug = null)
    {
        $data['settings'] = $this->getSettings();
        $productModel = new ProductModel();
        $categoryModel = new CategoryModel();
        
        $data['categories'] = $categoryModel->where('status', 1)->findAll();
        
        $catId = $this->request->getGet('category');
        $data['current_category_slug'] = '';
        
        if (!empty($categorySlug)) {
            $category = $categoryModel->where('slug', $categorySlug)->first();
            if ($category) {
                $catId = $category['id'];
                $data['current_category_slug'] = $categorySlug;
            }
        }
        
        $search = $this->request->getGet('search');
        
        if (!empty($catId)) {
            $productModel->where('category_id', $catId);
        }
        
        if (!empty($search)) {
            $productModel->groupStart()
                         ->like('name', $search)
                         ->orLike('short_description', $search)
                         ->groupEnd();
            $data['search'] = $search;
        }
        
        $data['products'] = $productModel->where('status', 1)->findAll();
        
        return view('front/products', $data);
    }

    public function productDetail($slug)
    {
        $data['settings'] = $this->getSettings();
        $productModel = new ProductModel();
        $data['product'] = $productModel->where('slug', $slug)->first();
        
        if (!$data['product']) throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        
        $data['meta_title'] = $data['product']['meta_title'] ?? null;
        $data['meta_description'] = $data['product']['meta_description'] ?? null;
        
        return view('front/product_detail', $data);
    }

    public function contact()
    {
        $data['settings'] = $this->getSettings();
        
        $pageModel = new PageModel();
        $data['page'] = $pageModel->where('slug', 'contact')->first();
        
        if ($this->request->getMethod() === 'POST') {
            $db = \Config\Database::connect();
            $insertData = [
                'type' => 'general',
                'name' => $this->request->getPost('name'),
                'email' => $this->request->getPost('email'),
                'phone' => $this->request->getPost('phone'),
                'message' => $this->request->getPost('message'),
                'created_at' => date('Y-m-d H:i:s')
            ];
            $db->table('enquiries')->insert($insertData);
            
            return redirect()->to('/contact')->with('success', 'Thank you for your enquiry. We will get back to you soon.');
        }
        
        $data['meta_title'] = $data['page']['meta_title'] ?? null;
        $data['meta_description'] = $data['page']['meta_description'] ?? null;
        
        return view('front/contact', $data);
    }

    public function gallery()
    {
        $data['settings'] = $this->getSettings();
        
        $pageModel = new PageModel();
        $data['page'] = $pageModel->where('slug', 'gallery')->first();

        $galleryModel = new \App\Models\GalleryModel();
        $galleryCategoryModel = new \App\Models\GalleryCategoryModel();

        $data['categories'] = $galleryCategoryModel->findAll();
        $data['images'] = $galleryModel->select('gallery.*, gallery_categories.slug as category_slug')
                                       ->join('gallery_categories', 'gallery_categories.id = gallery.category_id', 'left')
                                       ->findAll();

        $data['meta_title'] = $data['page']['meta_title'] ?? null;
        $data['meta_description'] = $data['page']['meta_description'] ?? null;

        return view('front/gallery', $data);
    }

    public function certification()
    {
        $data['settings'] = $this->getSettings();
        
        $certificationModel = new \App\Models\CertificationModel();
        $data['certifications'] = $certificationModel->where('status', 1)->orderBy('sort_order', 'ASC')->findAll();
        
        $data['meta_title'] = 'Certifications - ' . ($data['settings']['site_name'] ?? 'Premium Exports');
        $data['meta_description'] = 'Our quality certifications ensuring the highest standards.';
        
        return view('front/certification', $data);
    }

    public function requestSamples()
    {
        if (strtolower($this->request->getMethod()) !== 'post') {
            return $this->response->setStatusCode(405)->setJSON([
                'status' => 'error',
                'message' => 'Method not allowed.'
            ]);
        }

        $email = $this->request->getPost('email');
        if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Please provide a valid professional email address.'
            ]);
        }

        $productId = $this->request->getPost('product_id');
        $productId = !empty($productId) ? intval($productId) : null;

        // Get product details if productId is supplied to verify/reference it
        $productNameStr = '';
        if ($productId) {
            $productModel = new ProductModel();
            $product = $productModel->find($productId);
            if ($product) {
                $productNameStr = ' for ' . $product['name'];
            }
        }

        $db = \Config\Database::connect();
        $insertData = [
            'type' => 'sample',
            'product_id' => $productId,
            'name' => 'Sample Request Customer',
            'email' => $email,
            'phone' => '',
            'message' => 'Requested samples' . $productNameStr . '.',
            'status' => 'new',
            'created_at' => date('Y-m-d H:i:s')
        ];

        try {
            $db->table('enquiries')->insert($insertData);
            return $this->response->setJSON([
                'status' => 'success',
                'message' => 'Thank you! Your sample request has been submitted successfully.'
            ]);
        } catch (\Exception $e) {
            return $this->response->setStatusCode(500)->setJSON([
                'status' => 'error',
                'message' => 'Unable to save your request. Please try again later.'
            ]);
        }
    }
}
