<?php

namespace Core\App\Controllers;

use Core\App\Models\CustomerModel;
use Core\App\Services\WhatsAppService;

class CustomersController
{
    private CustomerModel $model;

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

    /* =====================================================
       LIST PAGE
    ===================================================== */
    public function index()
    {
        $filters = [
            'search'     => trim($_GET['search']     ?? ''),
            'tag'        => trim($_GET['tag']         ?? ''),
            'wilaya'     => trim($_GET['wilaya']      ?? ''),
            'min_orders' => (int)($_GET['min_orders'] ?? 0),
        ];
        $page      = max(1, (int)($_GET['page'] ?? 1));
        $perPage   = 50;
        $customers = $this->model->getList($filters, $page, $perPage);
        $total     = $this->model->countList($filters);
        $stats     = $this->model->getStats();
        $pages     = ceil($total / $perPage);

        require ROOT_PATH . '/admin/templates/header.php';
        require ROOT_PATH . '/admin/templates/customers/index.php';
        require ROOT_PATH . '/admin/templates/footer.php';
    }

    /* =====================================================
       CUSTOMER DETAILS PAGE
    ===================================================== */
    public function view($id)
    {
        $customer = $this->model->getById((int)$id);

        if (!$customer) {
            http_response_code(404);
            require ROOT_PATH . '/admin/templates/header.php';
            echo '<div class="content-wrapper"><section class="content pt-3"><div class="container-fluid"><div class="alert alert-warning">' . __('customers.not_found', 'Customer not found') . '</div></div></section></div>';
            require ROOT_PATH . '/admin/templates/footer.php';
            return;
        }

        $customerOrders   = $this->model->getOrdersByCustomer((int)$customer['id'], 20);
        $customerMessages = $this->model->getMessagesByCustomer((int)$customer['id'], 12);

        require ROOT_PATH . '/admin/templates/header.php';
        require ROOT_PATH . '/admin/templates/customers/view.php';
        require ROOT_PATH . '/admin/templates/footer.php';
    }

    /* =====================================================
       MARKETING CAMPAIGN PAGE
    ===================================================== */
    public function marketing()
    {
        $stats = $this->model->getStats();

        // Pre-check AI availability (avoid direct DB query inside template)
        $aiActive = false;
        try {
            $aiActive = (bool)\db()->query("SELECT COUNT(*) FROM ai_settings WHERE is_active=1 AND api_key != ''")->fetchColumn();
        } catch (\Throwable $e) {}

        require ROOT_PATH . '/admin/templates/header.php';
        require ROOT_PATH . '/admin/templates/customers/marketing.php';
        require ROOT_PATH . '/admin/templates/footer.php';
    }

    /* =====================================================
       SEND CAMPAIGN (AJAX)
    ===================================================== */
    public function sendCampaign()
    {
        header('Content-Type: application/json; charset=utf-8');

        $message  = trim($_POST['message']    ?? '');
        $tag      = trim($_POST['tag']         ?? '');
        $wilaya   = trim($_POST['wilaya']      ?? '');
        $minOrders = (int)($_POST['min_orders'] ?? 0);
        $campaign = trim($_POST['campaign']    ?? 'Campaign ' . date('d/m/Y'));

        if (!$message) {
            echo json_encode(['success' => false, 'error' => 'Message is required']);
            exit;
        }

        $service = WhatsAppService::fromSettings();
        if (!$service) {
            echo json_encode(['success' => false, 'error' => 'WhatsApp not configured']);
            exit;
        }

        $customers = $this->model->getPhonesForCampaign([
            'tag'        => $tag,
            'wilaya'     => $wilaya,
            'min_orders' => $minOrders ?: null,
        ]);

        if (empty($customers)) {
            echo json_encode(['success' => false, 'error' => 'No customers match the selected filters']);
            exit;
        }

        $sent   = 0;
        $failed = 0;
        $errors = [];

        foreach ($customers as $customer) {
            // إضافة اسم العميل في الرسالة
            $personalMsg = str_replace('{name}', $customer['full_name'], $message);
            $personalMsg = str_replace('{store_name}', $this->getStoreName(), $personalMsg);

            $result = $service->send($customer['phone_normalized'], $personalMsg);

            $this->model->logMessage([
                'type'        => 'marketing',
                'campaign'    => $campaign,
                'phone'       => $customer['phone_normalized'],
                'customer_id' => $customer['id'],
                'message'     => $personalMsg,
                'provider'    => $service->getProvider(),
                'status'      => $result['success'] ? 'sent' : 'failed',
                'error'       => $result['error'] ?? null,
            ]);

            if ($result['success']) {
                $sent++;
            } else {
                $failed++;
                if (count($errors) < 3) {
                    $errors[] = $result['error'] ?? 'Unknown error';
                }
            }

            // تأخير بسيط لتجنب rate limiting
            usleep(300000); // 300ms
        }

        echo json_encode([
            'success' => true,
            'sent'    => $sent,
            'failed'  => $failed,
            'total'   => count($customers),
            'errors'  => $errors,
        ]);
        exit;
    }

    /* =====================================================
       PREVIEW COUNT (AJAX)
    ===================================================== */
    public function previewCount()
    {
        header('Content-Type: application/json; charset=utf-8');

        $filters = [
            'tag'        => trim($_GET['tag']         ?? ''),
            'wilaya'     => trim($_GET['wilaya']       ?? ''),
            'min_orders' => (int)($_GET['min_orders']  ?? 0) ?: null,
        ];

        $count = count($this->model->getPhonesForCampaign($filters));
        echo json_encode(['count' => $count]);
        exit;
    }

    /* =====================================================
       SYNC — تزامن العملاء من الطلبات القديمة
       POST /admin/customers/sync
    ===================================================== */
    public function sync(): void
    {
        header('Content-Type: application/json; charset=utf-8');

        try {
            $result = $this->model->syncFromOrders();
            echo json_encode([
                'success' => true,
                'synced'  => $result['synced'],
                'skipped' => $result['skipped'],
            ]);
        } catch (\Throwable $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
        exit;
    }

    private function getStoreName(): string
    {
        try {
            $stmt = \db()->prepare("SELECT setting_value FROM settings WHERE setting_key='site_name' LIMIT 1");
            $stmt->execute();
            return $stmt->fetchColumn() ?: 'Store';
        } catch (\Throwable $e) {
            return 'Store';
        }
    }
}