<?php

namespace App\Controllers;

use App\Models\UserModel;
use App\Models\GalleryModel;
use App\Models\MenuPackageModel;
use App\Models\InquiryModel;
use App\Models\ServiceModel;

class Admin extends BaseController
{
    public function login()
    {
        if (session()->get('isLoggedIn')) {
            return redirect()->to(base_url('admin/dashboard'));
        }
        return view('admin/login');
    }

    public function login_submit()
    {
        $userModel = new UserModel();
        $username = $this->request->getPost('username');
        $password = $this->request->getPost('password');

        $user = $userModel->where('username', $username)->first();

        if ($user && password_verify($password, $user['password'])) {
            session()->set([
                'isLoggedIn' => true,
                'username'   => $user['username'],
            ]);
            return redirect()->to(base_url('admin/dashboard'))->with('success', 'Logged in successfully.');
        }

        return redirect()->to(base_url('admin/login'))->with('error', 'Invalid username or password.');
    }

    public function logout()
    {
        session()->destroy();
        return redirect()->to(base_url('admin/login'))->with('success', 'Logged out successfully.');
    }

    public function dashboard()
    {
        $galleryModel  = new GalleryModel();
        $menuModel     = new MenuPackageModel();
        $inquiryModel  = new InquiryModel();
        $serviceModel  = new ServiceModel();

        return view('admin/dashboard', [
            'title'          => 'Admin Dashboard | On Call',
            'activeTab'      => 'dashboard',
            'totalImages'    => $galleryModel->countAllResults(),
            'totalPackages'  => $menuModel->countAllResults(),
            'totalInquiries' => $inquiryModel->countAllResults(),
            'totalServices'  => $serviceModel->countAllResults(),
            'recentInquiries'=> $inquiryModel->orderBy('id', 'DESC')->limit(5)->find(),
        ]);
    }

    // ─── Gallery ─────────────────────────────────────────────────────────────────

    public function gallery()
    {
        $galleryModel = new GalleryModel();
        return view('admin/gallery', [
            'title'     => 'Manage Gallery | On Call',
            'activeTab' => 'gallery',
            'items'     => $galleryModel->orderBy('id', 'DESC')->findAll(),
        ]);
    }

    public function gallery_upload()
    {
        $validation = \Config\Services::validation();
        $validation->setRules([
            'title'    => 'required|min_length[3]|max_length[255]',
            'category' => 'required|in_list[Decor,Catering,Ceremonies]',
            'image'    => 'uploaded[image]|max_size[image,4096]|is_image[image]',
        ]);

        if (!$this->validate($validation->getRules())) {
            return redirect()->to(base_url('admin/gallery'))->with('error', 'Validation failed: ' . implode(', ', $this->validator->getErrors()));
        }

        $file = $this->request->getFile('image');
        if ($file->isValid() && !$file->hasMoved()) {
            $uploadPath = ROOTPATH . 'public/uploads/gallery/';
            if (!is_dir($uploadPath)) {
                mkdir($uploadPath, 0755, true);
            }

            $newName = $file->getRandomName();
            $file->move($uploadPath, $newName);

            $galleryModel = new GalleryModel();
            $galleryModel->insert([
                'title'      => $this->request->getPost('title'),
                'category'   => $this->request->getPost('category'),
                'image_path' => base_url('uploads/gallery/' . $newName),
                'created_at' => date('Y-m-d H:i:s'),
            ]);

            return redirect()->to(base_url('admin/gallery'))->with('success', 'Image uploaded successfully.');
        }

        return redirect()->to(base_url('admin/gallery'))->with('error', 'File upload failed.');
    }

    public function gallery_delete($id)
    {
        $galleryModel = new GalleryModel();
        $item = $galleryModel->find($id);

        if ($item) {
            $imagePath = $item['image_path'];
            // Only unlink local files (not remote URLs)
            if (strpos($imagePath, 'http://') === false && strpos($imagePath, 'https://') === false) {
                $localPath = ROOTPATH . 'public/' . ltrim($imagePath, '/');
                if (file_exists($localPath) && is_file($localPath)) {
                    @unlink($localPath);
                }
            } else {
                // Convert base_url to local path
                $localPath = str_replace(base_url(), ROOTPATH . 'public/', $imagePath);
                if (strpos($localPath, 'http') !== 0 && file_exists($localPath) && is_file($localPath)) {
                    @unlink($localPath);
                }
            }
            $galleryModel->delete($id);
            return redirect()->to(base_url('admin/gallery'))->with('success', 'Image deleted successfully.');
        }

        return redirect()->to(base_url('admin/gallery'))->with('error', 'Image not found.');
    }

    // ─── Menu ─────────────────────────────────────────────────────────────────

    public function menu()
    {
        $menuModel = new MenuPackageModel();
        return view('admin/menu', [
            'title'     => 'Manage Menu Packages | On Call',
            'activeTab' => 'menu',
            'packages'  => $menuModel->findAll(),
        ]);
    }

    public function menu_save()
    {
        $id = $this->request->getPost('id');
        $name = $this->request->getPost('name');
        $category = $this->request->getPost('category');
        $price = $this->request->getPost('price');
        $description = $this->request->getPost('description');
        
        $itemsText = $this->request->getPost('items');
        $itemsArray = array_filter(array_map('trim', explode("\n", $itemsText)));
        
        $servicesText = $this->request->getPost('services');
        $servicesArray = array_filter(array_map('trim', explode("\n", $servicesText)));

        $menuModel = new MenuPackageModel();
        $data = [
            'name'        => $name,
            'category'    => $category ?: 'Lunch',
            'price'       => $price,
            'description' => $description,
            'items'       => json_encode(array_values($itemsArray)),
            'services'    => json_encode(array_values($servicesArray)),
        ];

        if (empty($id)) {
            $data['created_at'] = date('Y-m-d H:i:s');
            $menuModel->insert($data);
            $msg = 'Package created successfully.';
        } else {
            $menuModel->update($id, $data);
            $msg = 'Package updated successfully.';
        }

        return redirect()->to(base_url('admin/menu'))->with('success', $msg);
    }

    public function menu_delete($id)
    {
        $menuModel = new MenuPackageModel();
        if ($menuModel->find($id)) {
            $menuModel->delete($id);
            return redirect()->to(base_url('admin/menu'))->with('success', 'Package deleted successfully.');
        }
        return redirect()->to(base_url('admin/menu'))->with('error', 'Package not found.');
    }

    // ─── Services ─────────────────────────────────────────────────────────────

    public function services()
    {
        $serviceModel = new ServiceModel();
        return view('admin/services', [
            'title'     => 'Manage Services | On Call',
            'activeTab' => 'services',
            'services'  => $serviceModel->orderBy('sort_order', 'ASC')->findAll(),
        ]);
    }

    public function services_save()
    {
        $id = $this->request->getPost('id');

        $featuresText  = $this->request->getPost('features');
        $featuresArray = array_filter(array_map('trim', explode("\n", $featuresText)));

        $serviceModel = new ServiceModel();
        
        // Handle file upload
        $imagePath = $this->request->getPost('existing_image') ?: '';
        $img = $this->request->getFile('image');

        if ($img && $img->isValid() && !$img->hasMoved()) {
            // Generate a random name
            $newName = $img->getRandomName();
            
            // Create uploads/services directory if not exists
            $uploadDir = FCPATH . 'uploads/services/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }
            
            $img->move($uploadDir, $newName);
            
            // Delete old uploaded image if we are replacing it
            if (!empty($imagePath)) {
                if (strpos($imagePath, 'uploads/services/') === 0) {
                    $oldFilePath = FCPATH . $imagePath;
                    if (file_exists($oldFilePath)) {
                        unlink($oldFilePath);
                    }
                }
            }
            
            $imagePath = 'uploads/services/' . $newName;
        }

        // If it's a new service and still no image path is set, set a default fallback
        if (empty($id) && empty($imagePath)) {
            $imagePath = 'images/service-wedding.png';
        }

        $data = [
            'title'       => $this->request->getPost('title'),
            'subtitle'    => $this->request->getPost('subtitle'),
            'description' => $this->request->getPost('description'),
            'features'    => json_encode(array_values($featuresArray)),
            'image_path'  => $imagePath,
        ];

        if (empty($id)) {
            // Auto-assign sort_order to maximum + 1
            $maxRow = $serviceModel->selectMax('sort_order')->first();
            $maxOrder = $maxRow ? (int)$maxRow['sort_order'] : 0;
            $data['sort_order'] = $maxOrder + 1;

            $data['created_at'] = date('Y-m-d H:i:s');
            $serviceModel->insert($data);
            $msg = 'Service created successfully.';
        } else {
            $serviceModel->update($id, $data);
            $msg = 'Service updated successfully.';
        }

        return redirect()->to(base_url('admin/services'))->with('success', $msg);
    }

    public function services_delete($id)
    {
        $serviceModel = new ServiceModel();
        $service = $serviceModel->find($id);
        if ($service) {
            $imagePath = $service['image_path'] ?? '';
            $serviceModel->delete($id);
            
            // Delete uploaded file if it exists and is under uploads/services/
            if (!empty($imagePath) && strpos($imagePath, 'uploads/services/') === 0) {
                $filePath = FCPATH . $imagePath;
                if (file_exists($filePath)) {
                    unlink($filePath);
                }
            }
            
            return redirect()->to(base_url('admin/services'))->with('success', 'Service deleted successfully.');
        }
        return redirect()->to(base_url('admin/services'))->with('error', 'Service not found.');
    }

    public function services_reorder()
    {
        $idsJson = $this->request->getPost('ids');
        $ids = json_decode($idsJson ?? '[]', true);

        if (empty($ids) || !is_array($ids)) {
            return $this->response->setJSON(['success' => false, 'message' => 'No IDs provided.']);
        }

        $serviceModel = new ServiceModel();
        foreach ($ids as $index => $id) {
            $serviceModel->update((int)$id, ['sort_order' => $index + 1]);
        }

        return $this->response->setJSON(['success' => true, 'message' => 'Order updated successfully.']);
    }

    // ─── Inquiries ────────────────────────────────────────────────────────────

    public function inquiries()
    {
        $inquiryModel = new InquiryModel();
        return view('admin/inquiries', [
            'title'     => 'View Inquiries | On Call',
            'activeTab' => 'inquiries',
            'inquiries' => $inquiryModel->orderBy('id', 'DESC')->findAll(),
        ]);
    }

    public function inquiry_delete($id)
    {
        $inquiryModel = new InquiryModel();
        if ($inquiryModel->find($id)) {
            $inquiryModel->delete($id);
            return redirect()->to(base_url('admin/inquiries'))->with('success', 'Inquiry deleted successfully.');
        }
        return redirect()->to(base_url('admin/inquiries'))->with('error', 'Inquiry not found.');
    }
}
