<?php
declare(strict_types=1);

namespace App\Modules\Inventory\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\Inventory\Models\Supplier;

class SupplierController extends Controller
{
    public function index(Request $request): Response
    {
        $filters = [
            'q'         => trim((string) $request->get('q', '')),
            'is_active' => $request->get('is_active', ''),
        ];

        $page = max(1, (int) $request->get('page', 1));
        $result = Supplier::search($filters, 25, $page);

        return $this->view('Inventory.Views.suppliers.index', [
            'suppliers'  => $result['data'],
            'pagination' => $result['pagination'],
            'filters'    => $filters,
        ]);
    }

    public function create(Request $request): Response
    {
        return $this->view('Inventory.Views.suppliers.form', [
            'supplier' => null,
        ]);
    }

    public function store(Request $request): Response
    {
        $data = $this->extractData($request);
        $errors = $this->validateSupplier($data);

        // Unique code
        if ($data['code'] !== '') {
            $existing = Supplier::query()->where('code', '=', $data['code'])->first();
            if ($existing) {
                $errors[] = 'كود المورد مستخدم بالفعل';
            }
        }

        if (!empty($errors)) {
            return $this->flashErrorsAndRedirect($errors, $request, '/inventory/suppliers/create');
        }

        $supplier = Supplier::create($data);

        return $this->redirect('/inventory/suppliers/' . $supplier->id)->withSuccess('تم إضافة المورد بنجاح');
    }

    public function show(Request $request, string $id): Response
    {
        $supplier = Supplier::find((int) $id);
        if (!$supplier) {
            return $this->redirect('/inventory/suppliers')->withError('المورد غير موجود');
        }

        $db = App::getInstance()->db();
        $recentPOs = $db->select(
            "SELECT * FROM `purchase_orders` WHERE `supplier_id` = ? ORDER BY `created_at` DESC LIMIT 10",
            [(int) $id]
        );

        return $this->view('Inventory.Views.suppliers.show', [
            'supplier'  => $supplier,
            'recentPOs' => $recentPOs,
        ]);
    }

    public function edit(Request $request, string $id): Response
    {
        $supplier = Supplier::find((int) $id);
        if (!$supplier) {
            return $this->redirect('/inventory/suppliers')->withError('المورد غير موجود');
        }

        return $this->view('Inventory.Views.suppliers.form', [
            'supplier' => $supplier,
        ]);
    }

    public function update(Request $request, string $id): Response
    {
        $supplier = Supplier::find((int) $id);
        if (!$supplier) {
            return $this->redirect('/inventory/suppliers')->withError('المورد غير موجود');
        }

        $data = $this->extractData($request);
        $errors = $this->validateSupplier($data);

        // Unique code (exclude current)
        if ($data['code'] !== '') {
            $existing = Supplier::query()
                ->where('code', '=', $data['code'])
                ->whereRaw('`id` != ?', [(int) $id])
                ->first();
            if ($existing) {
                $errors[] = 'كود المورد مستخدم بالفعل';
            }
        }

        if (!empty($errors)) {
            return $this->flashErrorsAndRedirect($errors, $request, '/inventory/suppliers/' . $id . '/edit');
        }

        $supplier->update($data);

        return $this->redirect('/inventory/suppliers/' . $id)->withSuccess('تم تحديث بيانات المورد بنجاح');
    }

    private function extractData(Request $request): array
    {
        return [
            'code'           => strtoupper(trim((string) $request->post('code', ''))),
            'name_ar'        => trim((string) $request->post('name_ar', '')),
            'name_en'        => trim((string) $request->post('name_en', '')) ?: null,
            'contact_person' => trim((string) $request->post('contact_person', '')) ?: null,
            'phone'          => trim((string) $request->post('phone', '')) ?: null,
            'email'          => trim((string) $request->post('email', '')) ?: null,
            'address'        => trim((string) $request->post('address', '')) ?: null,
            'tax_number'     => trim((string) $request->post('tax_number', '')) ?: null,
            'payment_terms'  => trim((string) $request->post('payment_terms', '')) ?: null,
            'rating'         => ((int) $request->post('rating', 0)) ?: null,
            'is_active'      => (int) ($request->post('is_active', 1)),
            'notes'          => trim((string) $request->post('notes', '')) ?: null,
        ];
    }

    private function validateSupplier(array $data): array
    {
        $errors = [];
        if ($data['code'] === '') {
            $errors[] = 'كود المورد مطلوب';
        }
        if ($data['name_ar'] === '' || mb_strlen($data['name_ar']) < 2) {
            $errors[] = 'اسم المورد بالعربي مطلوب (حرفان على الأقل)';
        }
        return $errors;
    }

    private function flashErrorsAndRedirect(array $errors, Request $request, string $url): Response
    {
        $session = App::getInstance()->session();
        $session->flash('_alerts', array_map(fn($e) => ['type' => 'error', 'message' => $e], $errors));
        $session->flash('_old_input', $request->all());
        return $this->redirect($url);
    }
}
