<?php

namespace App\Modules\Admin\Controllers;

use CodeIgniter\Controller;
use App\Modules\Frontend\Models\TourModel;

class TourController extends Controller
{
    protected $model;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->model = new TourModel();
    }

    public function index()
    {
        return view('App\Modules\Admin\Views\tours\index', [
            'tours' => $this->model->orderBy('created_at', 'DESC')->findAll()
        ]);
    }

    public function create()
    {
        return view('App\Modules\Admin\Views\tours\form', [
            'tour' => null,
            'errors' => []
        ]);
    }

    public function store()
    {
        helper('text');

        // Manual validation (no file rules)
        $title = $this->request->getPost('title');
        $duration_days = $this->request->getPost('duration_days');
        $difficulty = $this->request->getPost('difficulty');
        $route = $this->request->getPost('route');
        $price_usd = $this->request->getPost('price_usd');
        $description = $this->request->getPost('description');

        $errors = [];
        if (empty($title)) $errors['title'] = 'Title is required.';
        if (empty($duration_days) || !is_numeric($duration_days) || $duration_days < 1) $errors['duration_days'] = 'Valid duration (days) is required.';
        if (empty($difficulty) || !in_array($difficulty, ['beginner','intermediate','advanced'])) $errors['difficulty'] = 'Select a valid difficulty.';
        if (empty($route)) $errors['route'] = 'Route is required.';
        if (empty($price_usd) || !is_numeric($price_usd) || $price_usd <= 0) $errors['price_usd'] = 'Valid price is required.';
        if (empty($description)) $errors['description'] = 'Description is required.';

        // If validation fails, re-render form
        if (!empty($errors)) {
            return view('App\Modules\Admin\Views\tours\form', [
                'tour' => $this->request->getPost(),
                'errors' => $errors
            ]);
        }

        // Build data
        $data = [
            'title' => $title,
            'slug' => url_title($title, '-', true),
            'description' => $description,
            'route' => $route,
            'duration_days' => (int)$duration_days,
            'difficulty' => $difficulty,
            'price_usd' => (float)$price_usd,
            'is_active' => (bool)$this->request->getPost('is_active'),
            'images' => '[]' // default empty JSON array
        ];

        // Handle image uploads
        $images = [];
        $files = $this->request->getFiles();
        if (!empty($files['images']) && is_array($files['images'])) {
            foreach ($files['images'] as $file) {
                if ($file && $file->isValid() && !$file->hasMoved()) {
                    if ($file->getSize() <= (2048 * 1024)) { // <= 2MB
                        $ext = $file->getExtension();
                        if (in_array($ext, ['jpg', 'jpeg', 'png', 'gif'])) {
                            $newName = $file->getRandomName();
                            $file->move(FCPATH . 'assets/uploads/tours', $newName);
                            $images[] = $newName;
                        }
                    }
                }
            }
        }
        $data['images'] = json_encode($images);

        // Save
        if ($this->model->insert($data)) {
            return redirect()->to('/admin/tours')->with('success', 'Tour created successfully.');
        }

        // Fallback error
        return view('App\Modules\Admin\Views\tours\form', [
            'tour' => $data,
            'errors' => ['system' => 'Failed to save tour. Please try again.']
        ]);
    }

    public function edit($id)
    {
        $tour = $this->model->find($id);
        if (!$tour) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }
        return view('App\Modules\Admin\Views\tours\form', [
            'tour' => $tour,
            'errors' => []
        ]);
    }

    public function update($id)
    {
        helper('text');

        $tour = $this->model->find($id);
        if (!$tour) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }

        $title = $this->request->getPost('title');
        $duration_days = $this->request->getPost('duration_days');
        $difficulty = $this->request->getPost('difficulty');
        $route = $this->request->getPost('route');
        $price_usd = $this->request->getPost('price_usd');
        $description = $this->request->getPost('description');

        $errors = [];
        if (empty($title)) $errors['title'] = 'Title is required.';
        if (empty($duration_days) || !is_numeric($duration_days) || $duration_days < 1) $errors['duration_days'] = 'Valid duration (days) is required.';
        if (empty($difficulty) || !in_array($difficulty, ['beginner','intermediate','advanced'])) $errors['difficulty'] = 'Select a valid difficulty.';
        if (empty($route)) $errors['route'] = 'Route is required.';
        if (empty($price_usd) || !is_numeric($price_usd) || $price_usd <= 0) $errors['price_usd'] = 'Valid price is required.';
        if (empty($description)) $errors['description'] = 'Description is required.';

        if (!empty($errors)) {
            return view('App\Modules\Admin\Views\tours\form', [
                'tour' => array_merge($tour, $this->request->getPost()),
                'errors' => $errors
            ]);
        }

        $data = [
            'title' => $title,
            'slug' => url_title($title, '-', true),
            'description' => $description,
            'route' => $route,
            'duration_days' => (int)$duration_days,
            'difficulty' => $difficulty,
            'price_usd' => (float)$price_usd,
            'is_active' => (bool)$this->request->getPost('is_active')
        ];

        // Preserve existing + add new images
        $images = json_decode($tour['images'], true) ?: [];
        $files = $this->request->getFiles();
        if (!empty($files['images']) && is_array($files['images'])) {
            foreach ($files['images'] as $file) {
                if ($file && $file->isValid() && !$file->hasMoved()) {
                    if ($file->getSize() <= (2048 * 1024)) {
                        $ext = $file->getExtension();
                        if (in_array($ext, ['jpg', 'jpeg', 'png', 'gif'])) {
                            $newName = $file->getRandomName();
                            $file->move(FCPATH . 'assets/uploads/tours', $newName);
                            $images[] = $newName;
                        }
                    }
                }
            }
        }
        $data['images'] = json_encode(array_unique($images));

        if ($this->model->update($id, $data)) {
            return redirect()->to('/admin/tours')->with('success', 'Tour updated successfully.');
        }

        return view('App\Modules\Admin\Views\tours\form', [
            'tour' => array_merge($tour, $data),
            'errors' => ['system' => 'Failed to update tour.']
        ]);
    }

    public function delete($id)
    {
        $this->model->delete($id);
        return redirect()->to('/admin/tours')->with('info', 'Tour deleted.');
    }
}