<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\RescueServiceModel;

class Rescue extends BaseController
{
    public function index()
    {
        $db = \Config\Database::connect();
        $builder = $db->table('orders')
            ->select('orders.*, u.phone as user_phone, u.display_name as user_name, u.username as user_username')
            ->join('users u', 'u.id = orders.user_id', 'left')
            ->where('orders.order_type', 'rescue')
            ->orderBy('orders.created_at', 'DESC');
        $q = $this->request->getGet('q');
        if ($q !== null && $q !== '') {
            $q = trim($q);
            $builder->groupStart()
                ->like('u.phone', $q)
                ->orLike('u.display_name', $q)
                ->orLike('u.username', $q)
                ->groupEnd();
        }
        $dateFrom = $this->request->getGet('date_from');
        if ($dateFrom !== null && $dateFrom !== '') {
            $from = date('Y-m-d', strtotime($dateFrom));
            if ($from) {
                $builder->where('orders.created_at >=', $from . ' 00:00:00');
            }
        }
        $dateTo = $this->request->getGet('date_to');
        if ($dateTo !== null && $dateTo !== '') {
            $to = date('Y-m-d', strtotime($dateTo));
            if ($to) {
                $builder->where('orders.created_at <=', $to . ' 23:59:59');
            }
        }
        $status = $this->request->getGet('status');
        if ($status !== null && $status !== '') {
            $allowed = ['pending', 'paid', 'dispatched', 'delivered', 'cancelled'];
            if (in_array($status, $allowed, true)) {
                $builder->where('orders.status', $status);
            } elseif ($status === 'pending_group') {
                $builder->whereIn('orders.status', ['pending', 'paid', 'dispatched']);
            }
        }
        $rescueOrders = $builder->get()->getResult();
        $services = model(RescueServiceModel::class)->findAll();
        $content = view('admin/rescue_list', [
            'orders' => $rescueOrders,
            'services' => $services,
            'filter_q' => $q ?? '',
            'filter_date_from' => $dateFrom ?? '',
            'filter_date_to' => $dateTo ?? '',
            'filter_status' => $status ?? '',
        ]);
        return view('admin/layout', ['title' => 'Rescue+', 'content' => $content]);
    }

    public function saveService()
    {
        $name  = $this->request->getPost('name');
        $price = (float) $this->request->getPost('price');
        if ($name !== null && $name !== '') {
            model(RescueServiceModel::class)->insert(['name' => $name, 'price' => $price, 'status' => 'active']);
        }
        return redirect()->to(base_url('admin/rescue'))->with('message', 'Service added.');
    }
}
