<?php

namespace Core\App\Controllers;

use Core\App\Models\TeamMemberModel;
use Core\App\Models\OrderLifecycleEventModel;
use Core\App\Models\OrderWorkflowModel;
use Core\System\Response;

class TeamController
{
    protected TeamMemberModel $model;
    protected OrderWorkflowModel $workflow;

    public function __construct()
    {
        $this->model = new TeamMemberModel();
        $this->workflow = new OrderWorkflowModel();
        $this->requireRole(['owner', 'manager']);
    }

    /* =====================================================
       قائمة الفريق
    ===================================================== */
    public function index(): void
    {
        $members  = $this->model->getAll();
        $teamStats = $this->model->getTeamStats(null, 30);

        // دمج الإحصائيات مع الأعضاء
        $statsMap = [];
        foreach ($teamStats as $s) {
            $statsMap[$s['id']] = $s;
        }

        view_admin('team/index', compact('members', 'statsMap'));
    }

    /* =====================================================
       صفحة إضافة عضو
    ===================================================== */
    public function create(): void
    {
        view_admin('team/form', ['member' => null, 'roles' => TeamMemberModel::ROLES]);
    }

    /* =====================================================
       حفظ عضو جديد
    ===================================================== */
    public function store(): void
    {
        \Core\System\Csrf::check();

        $data = [
            'username' => trim($_POST['username'] ?? ''),
            'password' => trim($_POST['password'] ?? ''),
            'email'    => trim($_POST['email']    ?? ''),
            'role'     => $_POST['role']          ?? 'confirmer',
        ];

        if (empty($data['username']) || empty($data['password'])) {
            $_SESSION['error'] = __('team.error_required', 'يرجى ملء جميع الحقول المطلوبة');
            Response::redirect('/admin/team/create');
            return;
        }

        if (!array_key_exists($data['role'], TeamMemberModel::ROLES)) {
            $data['role'] = 'confirmer';
        }

        // منع إنشاء owner إضافي
        if ($data['role'] === 'owner') $data['role'] = 'manager';

        $this->model->create($data);
        $_SESSION['success'] = __('team.created', 'تم إضافة العضو بنجاح');
        Response::redirect('/admin/team');
    }

    /* =====================================================
       صفحة تعديل عضو
    ===================================================== */
    public function edit(int $id): void
    {
        $member = $this->model->getById($id);
        if (!$member) {
            Response::redirect('/admin/team');
            return;
        }
        view_admin('team/form', ['member' => $member, 'roles' => TeamMemberModel::ROLES]);
    }

    /* =====================================================
       تحديث عضو
    ===================================================== */
    public function update(int $id): void
    {
        \Core\System\Csrf::check();

        $member = $this->model->getById($id);
        if (!$member) {
            Response::redirect('/admin/team');
            return;
        }

        $data = [
            'role'      => $_POST['role']      ?? $member['role'],
            'email'     => trim($_POST['email'] ?? ''),
            'is_active' => isset($_POST['is_active']) ? 1 : 0,
            'password'  => trim($_POST['password'] ?? ''),
        ];

        // منع تغيير دور الـ owner
        if ($member['role'] === 'owner') $data['role'] = 'owner';
        if ($data['role'] === 'owner')   $data['role'] = 'manager';

        $this->model->update($id, $data);
        $_SESSION['success'] = __('team.updated', 'تم تحديث العضو بنجاح');
        Response::redirect('/admin/team');
    }

    /* =====================================================
       حذف عضو
    ===================================================== */
    public function delete(int $id): void
    {
        $deleted = $this->model->delete($id);
        $_SESSION[$deleted ? 'success' : 'error'] = $deleted
            ? __('team.deleted', 'تم حذف العضو')
            : __('team.cannot_delete_owner', 'لا يمكن حذف مالك المتجر');
        Response::redirect('/admin/team');
    }

    /* =====================================================
       تبديل تفعيل عضو
    =====================================================*/
    public function toggle(int $id): void
    {
        $member = $this->model->getById($id);
        if ($member && $member['role'] !== 'owner') {
            $this->model->toggleActive($id);
        }
        Response::redirect('/admin/team');
    }

    /* =====================================================
       تعيين طلب لموظف يدوياً
    ===================================================== */
    public function assignOrder(): void
    {
        \Core\System\Csrf::check();

        $orderId = (int)($_POST['order_id'] ?? 0);
        $adminId = (int)($_POST['admin_id'] ?? 0);
        $mode    = trim((string)($_POST['assign_mode'] ?? 'manual'));

        if ($orderId && $mode === 'auto') {
            $assigned = $this->workflow->autoAssignOrder(
                $orderId,
                'manager_auto_assignment',
                [],
                (int)($_SESSION['admin_id'] ?? 0),
                trim((string)($_POST['assign_note'] ?? ''))
            );
            $_SESSION[$assigned ? 'success' : 'error'] = $assigned
                ? __('team.workflow_auto_assigned', 'تم توزيع الطلب تلقائيًا حسب القواعد.')
                : __('team.workflow_no_agent', 'لم يتم العثور على موظف مناسب لهذا الطلب.');
        } elseif ($orderId && $adminId) {
            $this->workflow->assignOrderToAdmin(
                $orderId,
                $adminId,
                (int)($_SESSION['admin_id'] ?? 0),
                'manager_manual_assignment',
                trim((string)($_POST['assign_note'] ?? ''))
            );
            $_SESSION['success'] = __('team.workflow_manual_assigned', 'تم إسناد الطلب يدويًا بنجاح.');
        }

        Response::redirect('/admin/orders/view/' . $orderId);
    }

    /* =====================================================
       إحصائيات أداء الفريق
    ===================================================== */
    public function stats(): void
    {
        $days      = (int)($_GET['days'] ?? 30);
        $teamStats = $this->model->getTeamStats(null, $days);

        view_admin('team/stats', compact('teamStats', 'days'));
    }

    public function workflow(): void
    {
        $range = trim((string)($_GET['range'] ?? 'week'));
        $from = trim((string)($_GET['from'] ?? '')) ?: null;
        $to = trim((string)($_GET['to'] ?? '')) ?: null;
        $dashboard = $this->workflow->getDashboard($range, $from, $to);
        $assignableMembers = $this->workflow->getAssignableMembers();
        $window = $dashboard['window'] ?? ['range' => $range, 'start' => null, 'end' => null];

        view_admin('team/workflow', [
            'range' => $window['range'] ?? $range,
            'window' => $window,
            'workflowSummary' => $dashboard['summary'] ?? [],
            'workflowRules' => $dashboard['rules'] ?? [],
            'workflowMembers' => $dashboard['members'] ?? [],
            'assignableMembers' => $assignableMembers,
        ]);
    }

    public function saveWorkflowRule(): void
    {
        \Core\System\Csrf::check();

        try {
            $this->workflow->saveRule($_POST, (int)($_SESSION['admin_id'] ?? 0));
            $_SESSION['success'] = __('team.workflow_rule_saved', 'تم حفظ قاعدة التوزيع بنجاح.');
        } catch (\Throwable $e) {
            $_SESSION['error'] = $e->getMessage() ?: __('team.workflow_rule_error', 'تعذر حفظ قاعدة التوزيع.');
        }

        Response::redirect('/admin/team/workflow');
    }

    public function toggleWorkflowRule(int $id): void
    {
        \Core\System\Csrf::check();
        $this->workflow->toggleRule($id);
        $_SESSION['success'] = __('team.workflow_rule_toggled', 'تم تحديث حالة القاعدة.');
        Response::redirect('/admin/team/workflow');
    }

    public function deleteWorkflowRule(int $id): void
    {
        \Core\System\Csrf::check();
        $this->workflow->deleteRule($id);
        $_SESSION['success'] = __('team.workflow_rule_deleted', 'تم حذف قاعدة التوزيع.');
        Response::redirect('/admin/team/workflow');
    }


    public function viewMember(int $id): void
    {
        $member = $this->model->getById($id);
        if (!$member) {
            \Core\System\Response::redirect('/admin/team');
            return;
        }

        $days = (int)($_GET['days'] ?? 30);
        $lifecycle = new OrderLifecycleEventModel();
        $summary = $lifecycle->getMemberSummary($id, $days);
        $assignedOrders = $this->model->getAssignedOrders($id);
        // latest member events
        $db = \db();
        $stmt = $db->prepare("SELECT e.*, o.full_name, o.phone, a.username AS admin_name FROM order_lifecycle_events e LEFT JOIN orders o ON o.id = e.order_id LEFT JOIN admins a ON a.id = e.admin_id WHERE e.admin_id = ? ORDER BY e.created_at DESC, e.id DESC LIMIT 25");
        $stmt->execute([$id]);
        $recentEvents = $stmt->fetchAll(\PDO::FETCH_ASSOC) ?: [];
        view_admin('team/member', compact('member', 'summary', 'days', 'assignedOrders', 'recentEvents'));
    }

    /* =====================================================
       Middleware — فحص الدور
    ===================================================== */
    private function requireRole(array $roles): void
    {
        $role = $_SESSION['admin_role'] ?? 'confirmer';
        if (!in_array($role, $roles, true)) {
            http_response_code(403);
            exit('403 Forbidden');
        }
    }

    /* =====================================================
       صفحة إدارة صلاحيات الأدوار
       مرئية للـ owner و manager فقط
    ===================================================== */
    public function permissions(): void
    {
        $allPerms    = \Core\App\Models\TeamMemberModel::ALL_PERMISSIONS;
        $allRoles    = \Core\App\Models\TeamMemberModel::ROLES;
        $rolePerms   = $this->model->getAllRolePermissions();

        view_admin('team/permissions', compact('allPerms', 'allRoles', 'rolePerms'));
    }

    /* =====================================================
       حفظ صلاحيات دور
    ===================================================== */
    public function savePermissions(): void
    {
        \Core\System\Csrf::check();

        $role = trim($_POST['role'] ?? '');

        if (!array_key_exists($role, \Core\App\Models\TeamMemberModel::ROLES) || $role === 'owner') {
            $_SESSION['error'] = __('team.invalid_role', 'دور غير صالح');
            \Core\System\Response::redirect('/admin/team/permissions');
            return;
        }

        $permissions = $_POST['permissions'] ?? [];
        $permissions = is_array($permissions) ? $permissions : [];

        $this->model->saveRolePermissions($role, $permissions);

        // مسح الـ cache لجميع الجلسات
        \Core\App\Models\TeamMemberModel::clearPermissionCache();

        $_SESSION['success'] = __('team.permissions_saved', 'تم حفظ الصلاحيات بنجاح');
        \Core\System\Response::redirect('/admin/team/permissions');
    }

}
