<?php
declare(strict_types=1);

namespace App\Controllers\Web;

use App\Middleware\AuthSession;
use App\Middleware\TenantScope;
use App\Models\Customer;
use Core\Controller;
use Core\Session;
use Core\Tool;

final class CustomersController extends Controller
{
    public function middleware(): array
    {
        return [AuthSession::class, TenantScope::class];
    }

    private function tenantId(): int
    {
        return (int) ($_SESSION['tenant_id'] ?? 0);
    }

    public function index(): void
    {
        $filters = [
            'status' => $_GET['status'] ?? null,
            'q'      => $_GET['q']      ?? null,
        ];
        $sort      = $_GET['sort'] ?? 'name_asc';
        $tenantId  = $this->tenantId();
        $active    = array_filter($filters);
        $perPage   = (int) ($_GET['per_page'] ?? 25);
        $perPage   = max(10, min($perPage, 100));
        $page      = max(1, (int) ($_GET['page'] ?? 1));
        $total     = Customer::countForTenant($tenantId, $active);
        $lastPage  = max(1, (int) ceil($total / $perPage));
        if ($page > $lastPage) $page = $lastPage;

        $this->render('customers/index', [
            'customers' => Customer::listForTenant($tenantId, $active, $perPage, ($page - 1) * $perPage, $sort),
            'sort'      => $sort,
            'filters'   => $filters,
            'flash'     => Session::flash('cust_msg'),
            'pager'     => [
                'total'    => $total,
                'per_page' => $perPage,
                'page'     => $page,
                'last'     => $lastPage,
                'from'     => $total > 0 ? ($page - 1) * $perPage + 1 : 0,
                'to'       => min($page * $perPage, $total),
            ],
        ]);
    }

    public function create(): void
    {
        $this->render('customers/form', [
            'customer' => null,
            'csrf'     => Tool::generateCsrf(),
        ]);
    }

    public function edit(int $id): void
    {
        $tenantId = $this->tenantId();
        $customer = Customer::findInTenant($tenantId, $id);
        if (!$customer) { Session::flash('cust_msg', 'Customer not found.'); redirect('/Customers'); }
        $this->render('customers/form', [
            'customer' => $customer,
            'csrf'     => Tool::generateCsrf(),
        ]);
    }

    public function save(): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') redirect('/Customers');
        if (!Tool::checkCsrf($_POST['_csrf'] ?? null)) {
            Session::flash('cust_msg', 'Session expired.'); redirect('/Customers');
        }
        $tenantId = $this->tenantId();
        $id = (int) ($_POST['customer_id'] ?? 0);

        if (trim((string) ($_POST['name'] ?? '')) === '') {
            Session::flash('cust_msg', 'Customer name is required.');
            redirect($id > 0 ? "/Customers/edit/{$id}" : '/Customers/create');
        }

        if ($id > 0) {
            Customer::update($tenantId, $id, $_POST);
            Session::flash('cust_msg', 'Customer updated.');
        } else {
            $id = Customer::create($tenantId, $_POST);
            Session::flash('cust_msg', 'Customer created.');
        }
        redirect("/Customers/edit/{$id}");
    }

    /**
     * Quick-add customer via AJAX — returns JSON with new customer_id.
     * POST /Customers/quickSave
     */
    public function quickSave(): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
            json_response(['error' => 'Method not allowed'], 405);
        }
        if (!Tool::checkCsrf($_POST['_csrf'] ?? null)) {
            json_response(['error' => 'Session expired'], 419);
        }
        $tenantId = $this->tenantId();
        $name = trim((string) ($_POST['name'] ?? ''));
        if ($name === '') {
            json_response(['error' => 'Customer name is required.'], 422);
        }
        $id = Customer::create($tenantId, [
            'name'           => $name,
            'contact_person' => $_POST['contact_person'] ?? null,
            'email'          => $_POST['email'] ?? null,
            'phone'          => $_POST['phone'] ?? null,
            'status'         => 'active',
        ]);
        json_response(['customer_id' => $id, 'name' => $name]);
    }

    public function delete(int $id): void
    {
        Customer::softDelete($this->tenantId(), $id);
        Session::flash('cust_msg', 'Customer deleted.');
        redirect('/Customers');
    }
}