<?php

namespace Core\App\Controllers;

use Core\App\Models\SuspiciousOrderModel;

class SuspiciousOrdersController
{
    private const PER_PAGE = 20;
    private SuspiciousOrderModel $model;

    public function __construct()
    {
        $this->model = new SuspiciousOrderModel();
    }

    public function index(): void
    {
        $tab     = $_GET['tab']  ?? 'orders';
        $page    = max(1, (int)($_GET['page'] ?? 1));
        $filters = [
            'risk'  => $_GET['risk']  ?? '',
            'phone' => trim($_GET['phone'] ?? ''),
        ];

        $offset        = ($page - 1) * self::PER_PAGE;
        $total         = $this->model->countSuspicious($filters);
        $total_pages   = max(1, (int)ceil($total / self::PER_PAGE));
        $orders        = $this->model->getSuspicious($filters, self::PER_PAGE, $offset);
        $stats         = $this->model->getStats();
        $banned_phones = $this->model->getBannedPhones();
        $current_page  = $page;

        // بيانات تبويب المحاولات
        $attempts_filter = trim($_GET['attempts_phone'] ?? '');
        $attempts        = $this->model->getAttempts($attempts_filter, self::PER_PAGE, $offset);
        $attempts_total  = $this->model->countAttempts($attempts_filter);
        $attempts_pages  = max(1, (int)ceil($attempts_total / self::PER_PAGE));

        $templatePath = ROOT_PATH . '/admin/templates/suspicious_orders/index.php';

        extract(compact(
            'orders', 'stats', 'banned_phones',
            'current_page', 'total_pages', 'filters',
            'tab', 'attempts', 'attempts_filter',
            'attempts_total', 'attempts_pages'
        ));

        require ROOT_PATH . '/admin/templates/header.php';
        require $templatePath;
        require ROOT_PATH . '/admin/templates/footer.php';
    }

    public function approve(int $orderId): void
    {
        $this->verifyCsrf();
        $ok = $this->model->approveOrder($orderId);
        $this->json(['success' => $ok]);
    }

    public function cancel(int $orderId): void
    {
        $this->verifyCsrf();
        $order = $this->model->getById($orderId);
        if (!$order) {
            $this->json(['success' => false, 'message' => 'Order not found']);
            return;
        }
        $ok = $this->model->cancelOrder($orderId);
        $this->json(['success' => $ok]);
    }

    public function banPhone(): void
    {
        $this->verifyCsrf();
        $body   = $this->jsonBody();
        $phone  = trim($body['phone']  ?? '');
        $reason = trim($body['reason'] ?? '');

        if (!$phone) {
            $this->json(['success' => false, 'message' => 'Phone is required']);
            return;
        }

        $this->model->banPhone($phone, $reason);

        if (!empty($body['order_id'])) {
            $this->model->cancelOrder((int)$body['order_id']);
        }

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

    public function unbanPhone(): void
    {
        $this->verifyCsrf();
        $body  = $this->jsonBody();
        $phone = trim($body['phone'] ?? '');

        if (!$phone) {
            $this->json(['success' => false, 'message' => 'Phone is required']);
            return;
        }

        $this->model->unbanPhone($phone);
        $this->json(['success' => true]);
    }

    /* ── CSRF يقرأ من POST body ── */
    private function verifyCsrf(): void
    {
        $body  = $this->jsonBody();
        $token = $body['_csrf'] ?? ($_POST['_csrf'] ?? '');

        if (
            empty($token) ||
            empty($_SESSION['_csrf']) ||
            !hash_equals($_SESSION['_csrf'], $token)
        ) {
            $this->json(['success' => false, 'message' => 'CSRF mismatch']);
            exit;
        }
    }

    private function json(array $data): void
    {
        if (!headers_sent()) {
            header('Content-Type: application/json; charset=utf-8');
        }
        echo json_encode($data);
        exit;
    }

    private function jsonBody(): array
    {
        static $body = null;
        if ($body === null) {
            $raw  = file_get_contents('php://input');
            $body = json_decode($raw, true) ?? [];
        }
        return $body;
    }
}