<?php

namespace Core\App\Controllers;

use Core\App\Models\PageviewsModel;

class DashboardController
{
    private \PDO $db;

    public function __construct()
    {
        $this->db = \db();
    }

    public function index()
    {
        // ── Role-based routing ──
        $role    = (string)($_SESSION['admin_role'] ?? 'owner');
        $adminId = (int)($_SESSION['admin_id']   ?? 0);

        if (!in_array($role, ['owner', 'manager', 'accountant'], true)) {
            $this->renderMemberDashboard($role, $adminId);
            return;
        }

        // ── Pageviews (الزوار)
        $stats        = new PageviewsModel();
        $today_views  = $stats->countToday();
        $today_unique = $stats->countUniqueToday();
        $online_users = $stats->countOnline();
        $engagement   = $stats->getEngagementToday();
        $compare      = $stats->compareWithYesterday();
        $returning    = $stats->returningVisitorsToday();
        $last7days    = $stats->getLast7Days();
        $top_pages_list = $stats->getTopPages(8);
        $weak_pages     = $stats->getWeakPages(5);

        $top_page = $top_pages_list[0] ?? ['page_url' => '-', 'product_name' => '—', 'views' => 0];

        // ── Timezone offset
        $tzOffset = (int)\db()->query(
            "SELECT setting_value FROM settings WHERE setting_key='timezone_offset' LIMIT 1"
        )->fetchColumn();

        $tzSql = $tzOffset >= 0
            ? "DATE_ADD(created_at, INTERVAL {$tzOffset} HOUR)"
            : "DATE_SUB(created_at, INTERVAL " . abs($tzOffset) . " HOUR)";

        // ── إحصائيات الطلبات اليوم
        $todayOrders = $this->db->query("
            SELECT
                COUNT(*) AS total,
                SUM(order_status = 'confirmed') AS confirmed,
                SUM(order_status = 'pending')   AS pending,
                SUM(order_status = 'rejected')  AS rejected,
                SUM(CASE WHEN order_status = 'confirmed'
                    THEN total_amount ELSE 0 END)  AS revenue
            FROM orders
            WHERE DATE({$tzSql}) = DATE(DATE_ADD(NOW(), INTERVAL {$tzOffset} HOUR))
        ")->fetch(\PDO::FETCH_ASSOC);

        // ── إحصائيات أمس (للمقارنة)
        $yesterdayOrders = $this->db->query("
            SELECT
                COUNT(*) AS total,
                SUM(order_status = 'confirmed') AS confirmed,
                SUM(CASE WHEN order_status = 'confirmed'
                    THEN total_amount ELSE 0 END) AS revenue
            FROM orders
            WHERE DATE({$tzSql}) = DATE(DATE_SUB(DATE_ADD(NOW(), INTERVAL {$tzOffset} HOUR), INTERVAL 1 DAY))
        ")->fetch(\PDO::FETCH_ASSOC);

        // ── إجمالي الطلبات المعلقة الآن
        $pendingNow = (int)$this->db->query(
            "SELECT COUNT(*) FROM orders WHERE order_status = 'pending'"
        )->fetchColumn();

        // ── معدل التأكيد (30 يوم)
        $confirmStats = $this->db->query("
            SELECT
                COUNT(*) AS total,
                SUM(order_status = 'confirmed') AS confirmed
            FROM orders
            WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
              AND order_status IN ('confirmed','rejected')
        ")->fetch(\PDO::FETCH_ASSOC);

        $confirmRate = ($confirmStats['total'] ?? 0) > 0
            ? round(($confirmStats['confirmed'] / $confirmStats['total']) * 100, 1)
            : 0;

        // ── رسم بياني آخر 14 يوم (طلبات + إيرادات)
        $chart14 = $this->db->query("
            SELECT
                DATE({$tzSql}) AS day,
                COUNT(*) AS orders,
                SUM(order_status = 'confirmed') AS confirmed,
                SUM(CASE WHEN order_status = 'confirmed'
                    THEN total_amount ELSE 0 END) AS revenue
            FROM orders
            WHERE created_at >= DATE_SUB(NOW(), INTERVAL 13 DAY)
            GROUP BY DATE({$tzSql})
            ORDER BY day ASC
        ")->fetchAll(\PDO::FETCH_ASSOC);

        // ── أحدث 5 طلبات
        $recentOrders = $this->db->query("
            SELECT id, full_name, phone, order_status, total_amount,
                   DATE_ADD(created_at, INTERVAL {$tzOffset} HOUR) AS created_local,
                   JSON_UNQUOTE(JSON_EXTRACT(extra,'$.product.name')) AS product_name
            FROM orders
            ORDER BY id DESC
            LIMIT 5
        ")->fetchAll(\PDO::FETCH_ASSOC);

        // ── Callbacks المؤجلة (من call_attempts)
        $callbacksCount = 0;
        try {
            $callbacksCount = (int)$this->db->query("
                SELECT COUNT(*) FROM order_call_attempts a
                JOIN orders o ON o.id = a.order_id
                WHERE a.id = (SELECT MAX(id) FROM order_call_attempts WHERE order_id = a.order_id)
                  AND a.result = 'callback_later'
                  AND o.order_status = 'pending'
            ")->fetchColumn();
        } catch (\Throwable $e) {}

        // ── currency
        $currency = \db()->query(
            "SELECT setting_value FROM settings WHERE setting_key='currency' LIMIT 1"
        )->fetchColumn() ?: 'DZD';

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

    /* =====================================================
     * Mini-dashboard for confirmer / shipping roles
     * ===================================================== */
    private function renderMemberDashboard(string $role, int $adminId): void
    {
        $currency = $this->db->query(
            "SELECT setting_value FROM settings WHERE setting_key='currency' LIMIT 1"
        )->fetchColumn() ?: 'DZD';

        // ── Today's performance from team_performance ──
        $todayPerf = ['confirmed' => 0, 'rejected' => 0, 'total' => 0];
        try {
            $stmt = $this->db->prepare(
                "SELECT confirmed, rejected, total FROM team_performance WHERE admin_id = ? AND date = CURDATE()"
            );
            $stmt->execute([$adminId]);
            $todayPerf = $stmt->fetch(\PDO::FETCH_ASSOC) ?: $todayPerf;
        } catch (\Throwable $e) {}

        // ── 30-day personal stats ──
        $monthPerf = ['confirmed' => 0, 'rejected' => 0, 'total' => 0];
        try {
            $stmt = $this->db->prepare(
                "SELECT SUM(confirmed) AS confirmed, SUM(rejected) AS rejected, SUM(total) AS total
                 FROM team_performance WHERE admin_id = ? AND date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)"
            );
            $stmt->execute([$adminId]);
            $monthPerf = $stmt->fetch(\PDO::FETCH_ASSOC) ?: $monthPerf;
        } catch (\Throwable $e) {}

        $confirmRate = ($monthPerf['total'] ?? 0) > 0
            ? round(($monthPerf['confirmed'] / $monthPerf['total']) * 100, 1)
            : 0;

        // ── Pending orders assigned to me ──
        $myPendingOrders = [];
        $myPendingCount  = 0;
        try {
            $stmt = $this->db->prepare("
                SELECT o.id, o.full_name, o.phone, o.total_amount, o.created_at,
                       JSON_UNQUOTE(JSON_EXTRACT(o.extra,'$.product.name')) AS product_name
                FROM orders o
                JOIN order_assignments oa ON oa.order_id = o.id
                WHERE oa.admin_id = ? AND o.order_status = 'pending'
                ORDER BY o.created_at DESC LIMIT 10
            ");
            $stmt->execute([$adminId]);
            $myPendingOrders = $stmt->fetchAll(\PDO::FETCH_ASSOC);
            $myPendingCount  = count($myPendingOrders);
        } catch (\Throwable $e) {}

        // ── Confirmed orders ready to ship (for shipping role) ──
        $readyToShip = [];
        $readyCount  = 0;
        if ($role === 'shipping') {
            try {
                $stmt = $this->db->query("
                    SELECT o.id, o.full_name, o.phone, o.total_amount, o.created_at,
                           JSON_UNQUOTE(JSON_EXTRACT(o.extra,'$.product.name')) AS product_name
                    FROM orders o
                    WHERE o.order_status = 'confirmed'
                      AND (JSON_UNQUOTE(JSON_EXTRACT(o.extra,'$.tracking.tracking_number')) IS NULL
                           OR JSON_UNQUOTE(JSON_EXTRACT(o.extra,'$.tracking.tracking_number')) = '')
                    ORDER BY o.created_at DESC LIMIT 10
                ");
                $readyToShip = $stmt->fetchAll(\PDO::FETCH_ASSOC);
                $readyCount  = count($readyToShip);
            } catch (\Throwable $e) {}

            // Total confirmed without tracking
            try {
                $readyCount = (int)$this->db->query("
                    SELECT COUNT(*) FROM orders WHERE order_status = 'confirmed'
                    AND (JSON_UNQUOTE(JSON_EXTRACT(extra,'$.tracking.tracking_number')) IS NULL
                         OR JSON_UNQUOTE(JSON_EXTRACT(extra,'$.tracking.tracking_number')) = '')
                ")->fetchColumn();
            } catch (\Throwable $e) {}
        }

        // ── Unread team messages ──
        $teamUnreadCount = 0;
        try {
            $teamUnreadCount = (new \Core\App\Models\TeamMessageModel())->totalUnread($adminId);
        } catch (\Throwable $e) {}

        // ── Upcoming meetings ──
        $upcomingMeetings = [];
        try {
            $upcomingMeetings = (new \Core\App\Models\TeamMeetingModel())->getUpcoming();
        } catch (\Throwable $e) {}

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