<?php
declare(strict_types=1);
namespace App\Controllers;

use App\Core\Controller;
use App\Core\SessionAuth;
use App\Repositories\CustomerRepository;
use App\Repositories\TailoringRepository;
use App\Repositories\SettingRepository;
use App\Services\AuditService;
use App\Services\WhatsAppService;

final class TailoringController extends Controller {
    private function auth(): SessionAuth {
        return app()->get(SessionAuth::class);
    }

    private function ensureTailoringAccess(): void {
        $auth = $this->auth();
        $auth->requireLogin();
        if (!$auth->canAccess('tailoring_store') && !$auth->canAccess('tailoring_ready')) {
            $auth->requirePageAccess('tailoring');
        }
    }

    public function index(): void {
        $this->ensureTailoringAccess();
        $q = trim((string)($_GET['q'] ?? ''));
        $repo = new TailoringRepository();
        $rows = $repo->searchOrders($q);
        $settings = (new SettingRepository())->allAssoc();
        $canCreate = $this->auth()->canAccess('tailoring_store');
        $canManageOrders = $this->auth()->canAccess('tailoring_ready');
        $this->view('tailoring/index', compact('rows', 'q', 'settings', 'canCreate', 'canManageOrders'));
    }

    public function store(): void {
        $this->auth()->requirePageAccess('tailoring_store');
        verify_csrf();

        $phone = trim((string)($_POST['phone'] ?? ''));
        $name = trim((string)($_POST['full_name'] ?? ''));
        $qty = max(1, min(50, (int)($_POST['qty'] ?? 1)));

        if ($phone === '') {
            flash('error', 'يرجى إدخال رقم الهاتف');
            redirect(base_url('?page=tailoring'));
        }
        if ($name === '') {
            flash('error', 'يرجى إدخال اسم العميل');
            redirect(base_url('?page=tailoring'));
        }

        $customerRepo = new CustomerRepository();
        $existingCustomer = $customerRepo->findByIdentifier($phone);
        if ($existingCustomer && (int)($existingCustomer['is_blacklisted'] ?? 0) === 1) {
            flash('error', 'هذا العميل محظور ولا يمكن تقديم خدمة له' . (!empty($existingCustomer['blacklist_reason']) ? ' — ' . $existingCustomer['blacklist_reason'] : ''));
            redirect(base_url('?page=tailoring'));
        }

        $customerId = $customerRepo->createOrUpdate([
            'full_name' => $name,
            'phone' => $phone,
            'civil_id' => '',
        ]);

        $repo = new TailoringRepository();
        $orderId = $repo->createOrder($customerId, $qty, (int)(current_user()['id'] ?? 1));

        (new AuditService())->log('tailoring', 'create', $orderId, [
            'customer_id' => $customerId,
            'qty' => $qty,
        ]);

        flash('success', 'تم إنشاء طلب الخياطة بنجاح');
        redirect(base_url('?page=tailoring_print&id=' . $orderId));
    }

    public function print(): void {
        $this->auth()->requirePageAccess('tailoring_print');
        $id = (int)($_GET['id'] ?? 0);
        $repo = new TailoringRepository();
        $order = $repo->findOrder($id);
        if (!$order) {
            http_response_code(404);
            $this->view('errors/404');
            return;
        }
        $barcodes = $repo->orderBarcodes($id);
        $this->view('tailoring/print', compact('order', 'barcodes'));
    }

    public function markReady(): void {
        $this->auth()->requirePageAccess('tailoring_ready');
        verify_csrf();
        $id = (int)($_POST['id'] ?? 0);
        if ($id <= 0) {
            flash('error', 'طلب غير صالح');
            redirect(base_url('?page=tailoring'));
        }

        $repo = new TailoringRepository();
        $order = $repo->markReady($id, (int)(current_user()['id'] ?? 1));
        if (!$order) {
            flash('error', 'تعذر تحديث الطلب');
            redirect(base_url('?page=tailoring'));
        }

        $settings = new SettingRepository();
        $template = $settings->get('tailoring_ready_template', 'مرحباً {name}، تم تجهيز المصر الخاصة بك. رقم التذكرة: {ticket_no}. يمكنك الحضور للاستلام.');
        $wa = new WhatsAppService($settings);
        if (!empty($order['phone'])) {
            $message = $wa->renderTemplate($template, [
                'name' => (string)$order['full_name'],
                'ticket_no' => (string)$order['ticket_no'],
                'phone' => (string)$order['phone'],
                'qty' => (string)$order['qty'],
            ]);
            $wa->send((string)$order['phone'], $message);
        }

        (new AuditService())->log('tailoring', 'mark_ready', $id, [
            'ticket_no' => $order['ticket_no'],
            'phone' => $order['phone'],
        ]);

        flash('success', 'تم تحديث الطلب إلى تم التجهيز وإرسال الإشعار للعميل');
        redirect(base_url('?page=tailoring'));
    }
}
