<?php
namespace Core\App\Controllers;

use Core\App\Models\Settings;
use Core\System\Response;
use Core\System\Csrf;
use Core\System\License\LicenseClient;

class SupportController
{
    private function getLicenseKey(): string
    {
        $settingsModel = new Settings();
        $rows = $settingsModel->getAll();
        return trim((string)($rows['license_key'] ?? ''));
    }

    public function index()
    {
        $licenseKey = $this->getLicenseKey();
        if ($licenseKey === '') {
            Response::redirect('/admin/updates-license?err=license_required');
        }

        $client = new LicenseClient();
        $res = $client->supportListTickets($licenseKey, defined('MTE_PRODUCT') ? (string)MTE_PRODUCT : 'MTEngine');

        $tickets = [];
        $error = null;

        if ($res === []) {
            $error = 'server_unreachable';
        } elseif (!empty($res['ok']) && !empty($res['tickets']) && is_array($res['tickets'])) {
            $tickets = $res['tickets'];
        } elseif (!empty($res['error'])) {
            $error = (string)$res['error'];
        }

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

    public function create()
    {
        Csrf::check();

        $licenseKey = $this->getLicenseKey();
        if ($licenseKey === '') {
            Response::redirect('/admin/support?err=license_required');
        }

        $subject  = trim((string)($_POST['subject'] ?? ''));
        $message  = trim((string)($_POST['message'] ?? ''));
        $priority = trim((string)($_POST['priority'] ?? 'normal'));

        if ($subject === '' || $message === '') {
            Response::redirect('/admin/support?err=missing_fields');
        }

        $client = new LicenseClient();
        $res = $client->supportCreateTicket(
            $licenseKey,
            $subject,
            $message,
            $priority,
            defined('MTE_PRODUCT') ? (string)MTE_PRODUCT : 'MTEngine'
        );

        if ($res === []) {
            Response::redirect('/admin/support?err=server_unreachable');
        }

        if (!empty($res['ok']) && !empty($res['ticket_id'])) {
            Response::redirect('/admin/support/view/' . (int)$res['ticket_id']);
        }

        Response::redirect('/admin/support?err=failed');
    }

    public function view($id)
    {
        $ticketId = (int)$id;

        $licenseKey = $this->getLicenseKey();
        if ($licenseKey === '') {
            Response::redirect('/admin/support?err=license_required');
        }

        $client = new LicenseClient();
        $res = $client->supportGetMessages(
            $licenseKey,
            $ticketId,
            defined('MTE_PRODUCT') ? (string)MTE_PRODUCT : 'MTEngine'
        );

        $messages = [];
        $error = null;

        // ✅ NEW: status used by view.php to hide reply instantly
        $ticketStatus = '';

        if ($res === []) {
            $error = 'server_unreachable';
        } elseif (!empty($res['ok']) && !empty($res['messages']) && is_array($res['messages'])) {
            $messages = $res['messages'];
        } else {
            $error = 'not_allowed';
        }

        // ✅ NEW: get status from list_tickets (same source as index.php)
        if ($error === null) {
            try {
                $list = $client->supportListTickets(
                    $licenseKey,
                    defined('MTE_PRODUCT') ? (string)MTE_PRODUCT : 'MTEngine'
                );

                if (!empty($list['ok']) && !empty($list['tickets']) && is_array($list['tickets'])) {
                    foreach ($list['tickets'] as $t) {
                        if ((int)($t['id'] ?? 0) === $ticketId) {
                            $ticketStatus = strtolower(trim((string)($t['status'] ?? '')));
                            break;
                        }
                    }
                }
            } catch (\Throwable $e) {
                // ignore
            }
        }

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

    public function reply($id)
    {
        Csrf::check();

        $ticketId = (int)$id;

        $licenseKey = $this->getLicenseKey();
        if ($licenseKey === '') {
            Response::redirect('/admin/support?err=license_required');
        }

        $message  = trim((string)($_POST['message'] ?? ''));
        if ($message === '') {
            Response::redirect('/admin/support/view/' . $ticketId . '?err=missing_message');
        }

        $client = new LicenseClient();
        $res = $client->supportReply(
            $licenseKey,
            $ticketId,
            $message,
            defined('MTE_PRODUCT') ? (string)MTE_PRODUCT : 'MTEngine'
        );

        if ($res === []) {
            Response::redirect('/admin/support/view/' . $ticketId . '?err=server_unreachable');
        }

        if (!empty($res['ok'])) {
            Response::redirect('/admin/support/view/' . $ticketId . '?saved=1');
        }

        // ✅ NEW: لو التذكرة مغلقة -> رسالة واضحة وتجربة احترافية
        $apiError = (string)($res['error'] ?? '');
        if ($apiError === 'ticket_closed') {
            Response::redirect('/admin/support/view/' . $ticketId . '?err=ticket_closed');
        }

        Response::redirect('/admin/support/view/' . $ticketId . '?err=failed');
    }

    // ✅ Close ticket (client side)
    public function close($id)
    {
        Csrf::check();

        $ticketId = (int)$id;

        $licenseKey = $this->getLicenseKey();
        if ($licenseKey === '') {
            Response::redirect('/admin/support?err=license_required');
        }

        if ($ticketId <= 0) {
            Response::redirect('/admin/support?err=invalid_ticket');
        }

        $client = new LicenseClient();
        $res = $client->supportCloseTicket(
            $licenseKey,
            $ticketId,
            defined('MTE_PRODUCT') ? (string)MTE_PRODUCT : 'MTEngine'
        );

        if ($res === []) {
            Response::redirect('/admin/support/view/' . $ticketId . '?err=server_unreachable');
        }

        if (!empty($res['ok'])) {
            Response::redirect('/admin/support/view/' . $ticketId . '?closed=1');
        }

        Response::redirect('/admin/support/view/' . $ticketId . '?err=failed');
    }
}
