<?php

namespace Modules\Services\Controllers;

use core\Controller;
use core\Auth;
use core\Database;
use core\Session;
use core\Security;
use Modules\Services\Models\Service;

class ServiceController extends Controller
{
    private Service $serviceModel;

    public function __construct()
    {
        parent::__construct();
        $this->serviceModel = new Service();
    }

    public function index(): void
    {
        $this->requirePermission('services_view');

        $db = Database::getInstance();
        $categoryId = $this->request->get('category_id', '');
        $search = $this->request->get('search', '');
        $page = max(1, (int)$this->request->get('page', 1));
        $perPage = PAGINATION_LIMIT;

        $query = $db->table('services s')
            ->select('s.*, sc.name as category_name, sc.slug as category_slug')
            ->leftJoin('service_categories sc', 's.category_id', '=', 'sc.id')
            ->where('s.deleted_at', 'IS', null);

        if (!empty($categoryId)) {
            $query->where('s.category_id', $categoryId);
        }

        if (!empty($search)) {
            $query->where(function ($q) use ($search) {
                $q->where('s.name', 'LIKE', '%' . $search . '%')
                  ->orWhere('s.description', 'LIKE', '%' . $search . '%');
            });
        }

        $services = $query->orderBy('s.name', 'ASC')->paginate($perPage, $page);

        $categories = $db->table('service_categories')
            ->where('deleted_at', 'IS', null)
            ->orderBy('sort_order', 'ASC')
            ->get();

        $this->view('Services/index', [
            'title' => 'Services',
            'breadcrumb' => ['Services' => url('services')],
            'services' => $services,
            'categories' => $categories,
            'categoryId' => $categoryId,
            'search' => $search,
        ]);
    }

    public function create(): void
    {
        $this->requirePermission('services_create');

        $db = Database::getInstance();
        $categories = $db->table('service_categories')
            ->where('is_active', 1)
            ->where('deleted_at', 'IS', null)
            ->orderBy('sort_order', 'ASC')
            ->get();

        $this->view('Services/create', [
            'title' => 'Add New Service',
            'breadcrumb' => [
                'Services' => url('services'),
                'Add New' => url('services/create'),
            ],
            'categories' => $categories,
        ]);
    }

    public function store(): void
    {
        $this->requirePermission('services_create');

        $validated = $this->validate([
            'name' => 'required|max_length:255',
            'category_id' => 'integer',
            'description' => 'max_length:2000',
            'duration_minutes' => 'required|integer|min:1|max:1440',
            'price' => 'required|numeric|min:0',
            'cost_price' => 'numeric|min:0',
            'tax_percent' => 'numeric|min:0|max:100',
            'color' => 'max_length:7',
            'commission_type' => 'in:percentage,fixed,none',
            'commission_value' => 'numeric|min:0',
            'is_active' => 'in:0,1',
        ]);

        $validated['slug'] = $this->serviceModel->generateSlug($validated['name']);
        $validated['is_active'] = $validated['is_active'] ?? 1;
        $validated['commission_value'] = $validated['commission_value'] ?? 0;
        $validated['cost_price'] = $validated['cost_price'] ?? 0;
        $validated['tax_percent'] = $validated['tax_percent'] ?? 0;
        $validated['category_id'] = !empty($validated['category_id']) ? $validated['category_id'] : null;

        $serviceId = $this->serviceModel->create($validated);
        $this->logActivity('create', 'Created service: ' . $validated['name']);
        $this->logAudit('create', 'services', $serviceId, null, $validated);

        $this->redirectWith(url('services'), 'success', 'Service created successfully.');
    }

    public function edit(int $id): void
    {
        $this->requirePermission('services_edit');

        $service = $this->serviceModel->find($id);
        if (!$service) {
            $this->redirectWith(url('services'), 'error', 'Service not found.');
        }

        $db = Database::getInstance();
        $categories = $db->table('service_categories')
            ->where('deleted_at', 'IS', null)
            ->orderBy('sort_order', 'ASC')
            ->get();

        $this->view('Services/edit', [
            'title' => 'Edit Service',
            'breadcrumb' => [
                'Services' => url('services'),
                'Edit' => url('services/edit/' . $id),
            ],
            'service' => $service,
            'categories' => $categories,
        ]);
    }

    public function update(int $id): void
    {
        $this->requirePermission('services_edit');

        $service = $this->serviceModel->find($id);
        if (!$service) {
            $this->redirectWith(url('services'), 'error', 'Service not found.');
        }

        $oldValues = (array)$service;

        $validated = $this->validate([
            'name' => 'required|max_length:255',
            'category_id' => 'integer',
            'description' => 'max_length:2000',
            'duration_minutes' => 'required|integer|min:1|max:1440',
            'price' => 'required|numeric|min:0',
            'cost_price' => 'numeric|min:0',
            'tax_percent' => 'numeric|min:0|max:100',
            'color' => 'max_length:7',
            'commission_type' => 'in:percentage,fixed,none',
            'commission_value' => 'numeric|min:0',
            'is_active' => 'in:0,1',
        ]);

        if ($validated['name'] !== $service->name) {
            $validated['slug'] = $this->serviceModel->generateSlug($validated['name'], $id);
        }
        $validated['is_active'] = $validated['is_active'] ?? 0;
        $validated['commission_value'] = $validated['commission_value'] ?? 0;
        $validated['cost_price'] = $validated['cost_price'] ?? 0;
        $validated['tax_percent'] = $validated['tax_percent'] ?? 0;
        $validated['category_id'] = !empty($validated['category_id']) ? $validated['category_id'] : null;

        $this->serviceModel->update($id, $validated);
        $this->logActivity('update', 'Updated service: ' . $validated['name']);
        $this->logAudit('update', 'services', $id, $oldValues, $validated);

        $this->redirectWith(url('services'), 'success', 'Service updated successfully.');
    }

    public function delete(int $id): void
    {
        $this->requirePermission('services_delete');

        $service = $this->serviceModel->find($id);
        if (!$service) {
            $this->redirectWith(url('services'), 'error', 'Service not found.');
        }

        $this->serviceModel->softDelete($id);
        $this->logActivity('delete', 'Deleted service: ' . $service->name);
        $this->logAudit('delete', 'services', $id, (array)$service, null);

        $this->redirectWith(url('services'), 'success', 'Service deleted successfully.');
    }

    public function search(): void
    {
        $this->requirePermission('services_view');

        $query = $this->request->get('q', '');
        $results = [];

        if (!empty($query)) {
            $results = $this->serviceModel->search($query);
        }

        $this->json([
            'success' => true,
            'data' => $results,
        ]);
    }
}
