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

use App\Core\Controller;
use App\Core\SessionAuth;
use App\Repositories\CustomerRepository;
use App\Services\AuditService;

final class CustomersController extends Controller {
    public function index(): void {
        app()->get(SessionAuth::class)->requireLogin();
        $q = trim((string)($_GET['q'] ?? ''));
        $scope = trim((string)($_GET['scope'] ?? 'all'));
        if (!in_array($scope, ['all','blacklist'], true)) $scope = 'all';

        $repo = new CustomerRepository();
        $rows = $repo->searchForAdmin($q, $scope);
        $stats = [
            'all' => count($repo->searchForAdmin('', 'all')),
            'blacklist' => count($repo->searchForAdmin('', 'blacklist')),
        ];
        $this->view('customers/index', compact('rows', 'q', 'scope', 'stats'));
    }

    public function blacklist(): void {
        app()->get(SessionAuth::class)->requireLogin();
        verify_csrf();
        $id = (int)($_POST['id'] ?? 0);
        $reason = trim((string)($_POST['reason'] ?? ''));
        if ($id <= 0 || $reason === '') {
            flash('error', 'يرجى تحديد العميل وسبب الحظر');
            redirect(base_url('?page=customers'));
        }
        $repo = new CustomerRepository();
        $customer = $repo->findById($id);
        if (!$customer) {
            flash('error', 'العميل غير موجود');
            redirect(base_url('?page=customers'));
        }
        $repo->blacklist($id, $reason);
        (new AuditService())->log('customers', 'blacklist', $id, ['reason' => $reason, 'phone' => $customer['phone'] ?? '']);
        flash('success', 'تم حظر العميل ونقله إلى القائمة السوداء');
        redirect(base_url('?page=customers'));
    }

    public function unblacklist(): void {
        app()->get(SessionAuth::class)->requireLogin();
        verify_csrf();
        $id = (int)($_POST['id'] ?? 0);
        if ($id <= 0) {
            flash('error', 'طلب غير صالح');
            redirect(base_url('?page=customers&scope=blacklist'));
        }
        $repo = new CustomerRepository();
        $customer = $repo->findById($id);
        if (!$customer) {
            flash('error', 'العميل غير موجود');
            redirect(base_url('?page=customers&scope=blacklist'));
        }
        $repo->unblacklist($id);
        (new AuditService())->log('customers', 'unblacklist', $id, ['phone' => $customer['phone'] ?? '']);
        flash('success', 'تم فك حظر العميل');
        redirect(base_url('?page=customers'));
    }
}
