<?php
include "session.php";
ini_set('display_errors', 0);
error_reporting(0);

header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");

require_once __DIR__ . '/../db.php';

try {
    $pdo->exec("
    CREATE TABLE IF NOT EXISTS `order_replacements` (
      `id`                    INT(11) NOT NULL AUTO_INCREMENT,
      `order_id`              INT(11) NOT NULL,
      `original_item_id`      INT(11) NOT NULL,
      `original_product_name` VARCHAR(255) NOT NULL,
      `original_variant_id`   INT(11) DEFAULT NULL,
      `original_attributes`   TEXT DEFAULT NULL,
      `original_quantity`     INT(11) NOT NULL DEFAULT 1,
      `original_unit_price`   DECIMAL(10,2) NOT NULL,
      `new_product_name`      VARCHAR(255) NOT NULL,
      `new_variant_id`        INT(11) DEFAULT NULL,
      `new_attributes`        TEXT DEFAULT NULL,
      `new_quantity`          INT(11) NOT NULL DEFAULT 1,
      `new_unit_price`        DECIMAL(10,2) NOT NULL,
      `status`                ENUM('pending','sent','received') NOT NULL DEFAULT 'pending',
      `notes`                 TEXT DEFAULT NULL,
      `created_at`            DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
      `updated_at`            DATETIME DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`),
      KEY `order_id` (`order_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");
} catch (Exception $e) {}

// ══ الفترة الزمنية ══
$period    = $_GET['period']    ?? 'all';
$date_from = trim($_GET['date_from'] ?? '');
$date_to   = trim($_GET['date_to']   ?? '');
$today     = date('Y-m-d');

switch ($period) {
    case 'today': $date_from = $today;                              $date_to = $today;        break;
    case 'week':  $date_from = date('Y-m-d',strtotime('-7 days')); $date_to = $today;        break;
    case 'month': $date_from = date('Y-m-01');                     $date_to = date('Y-m-t'); break;
    case 'year':  $date_from = date('Y-01-01');                    $date_to = date('Y-12-31');break;
    case 'custom': break;
    default:      $date_from = ''; $date_to = ''; break;
}

function buildDate($date_from, $date_to) {
    if (!empty($date_from) && !empty($date_to)) {
        return ['cond' => " AND DATE(o.order_date) BETWEEN ? AND ?", 'params' => [$date_from, $date_to]];
    } elseif (!empty($date_from)) {
        return ['cond' => " AND DATE(o.order_date) >= ?", 'params' => [$date_from]];
    } elseif (!empty($date_to)) {
        return ['cond' => " AND DATE(o.order_date) <= ?", 'params' => [$date_to]];
    }
    return ['cond' => '', 'params' => []];
}

function rq($pdo, $sql, $params = []) {
    $stmt = $pdo->prepare($sql);
    $stmt->execute(array_values($params));
    return $stmt;
}

// ── رسوم الإرجاع ──
$return_fees = [];
try {
    $s = $pdo->query("SELECT id, COALESCE(return_fee,200) AS return_fee FROM delivery_companies");
    foreach ($s->fetchAll() as $r) $return_fees[$r['id']] = floatval($r['return_fee']);
} catch (Exception $e) {}

// ══════════════════════════════════════════════════════════════
//  الإحصاءات الكلية — مع تمييز مسلّمة (مؤكدة) ومرسلة (متوقعة)
// ══════════════════════════════════════════════════════════════
$dt = buildDate($date_from, $date_to);

$totalSql = "
    SELECT
        COUNT(DISTINCT o.id)                                                                            AS total_orders,
        COUNT(DISTINCT CASE WHEN o.status_id=1 THEN o.id END)                                          AS pending_orders,
        COUNT(DISTINCT CASE WHEN o.status_id=2 THEN o.id END)                                          AS sent_orders,
        COUNT(DISTINCT CASE WHEN o.status_id=3 THEN o.id END)                                          AS delivered_orders,
        COUNT(DISTINCT CASE WHEN o.status_id=4 THEN o.id END)                                          AS cancelled_orders,

        /* ── إيرادات مؤكدة (مسلّمة فقط) ── */
        COALESCE(SUM(CASE WHEN o.status_id=3 THEN oi.quantity * oi.unit_price ELSE 0 END),0)           AS confirmed_revenue,
        COALESCE(SUM(CASE WHEN o.status_id=3 THEN oi.quantity * COALESCE(pv.purchase_price,0) ELSE 0 END),0) AS confirmed_cost,

        /* ── إيرادات متوقعة (مرسلة فقط) ── */
        COALESCE(SUM(CASE WHEN o.status_id=2 THEN oi.quantity * oi.unit_price ELSE 0 END),0)           AS expected_revenue,
        COALESCE(SUM(CASE WHEN o.status_id=2 THEN oi.quantity * COALESCE(pv.purchase_price,0) ELSE 0 END),0) AS expected_cost,

        /* ── الإجماليات الكلية (2+3+4) للعرض العام ── */
        COALESCE(SUM(oi.quantity * oi.unit_price),0)                                                   AS total_revenue,
        COALESCE(SUM(oi.quantity * COALESCE(pv.purchase_price,0)),0)                                   AS total_cost,

        /* ── تكاليف التوصيل المؤكدة (مسلّمة فقط) ── */
        COALESCE(SUM(
            CASE WHEN o.status_id=3
                 THEN COALESCE(o.delivery_price_modified,
                      (SELECT dp.price FROM delivery_prices dp
                       WHERE dp.wilaya_id=o.wilaya_id
                         AND dp.delivery_type=o.delivery_type
                         AND dp.delivery_company_id=o.delivery_company_id
                       LIMIT 1),0)
                 ELSE 0
            END
        ),0) AS confirmed_delivery_paid,

        /* ── تكاليف التوصيل المتوقعة (مرسلة فقط) ── */
        COALESCE(SUM(
            CASE WHEN o.status_id=2
                 THEN COALESCE(o.delivery_price_modified,
                      (SELECT dp.price FROM delivery_prices dp
                       WHERE dp.wilaya_id=o.wilaya_id
                         AND dp.delivery_type=o.delivery_type
                         AND dp.delivery_company_id=o.delivery_company_id
                       LIMIT 1),0)
                 ELSE 0
            END
        ),0) AS expected_delivery_paid,

        /* ── رسوم الإرجاع (ملغاة فقط) ── */
        COALESCE(SUM(
            CASE WHEN o.status_id=4
                 THEN COALESCE((SELECT dc.return_fee FROM delivery_companies dc WHERE dc.id=o.delivery_company_id LIMIT 1),200)
                 ELSE 0
            END
        ),0) AS total_return_fees

    FROM orders o
    LEFT JOIN order_items oi ON o.id=oi.order_id
    LEFT JOIN product_variants pv ON oi.product_variant_id=pv.id
    WHERE 1=1 {$dt['cond']}
";
$totals = rq($pdo, $totalSql, $dt['params'])->fetch();
if (!$totals) $totals = [];

// ══════════════════════════════════════════════════════════════
//  تكلفة توصيل الاستبدالات — مؤكدة ومتوقعة
// ══════════════════════════════════════════════════════════════
$replacementDeliveryCost_confirmed  = 0;
$replacementDeliveryCost_expected   = 0;
$replacementDeliveryByOrder         = [];
$replacementCountByOrder            = [];
$totalReplacementsCount             = 0;
try {
    $dt2 = buildDate($date_from, $date_to);
    $replSql = "
        SELECT
            orep.order_id,
            o.status_id,
            COUNT(orep.id) AS repl_count,
            COALESCE(o.delivery_price_modified,
                (SELECT dp.price FROM delivery_prices dp
                 WHERE dp.wilaya_id=o.wilaya_id
                   AND dp.delivery_type=o.delivery_type
                   AND dp.delivery_company_id=o.delivery_company_id
                 LIMIT 1),0) AS delivery_cost
        FROM order_replacements orep
        JOIN orders o ON orep.order_id=o.id
        WHERE o.status_id IN (2,3)
        {$dt2['cond']}
        GROUP BY orep.order_id
    ";
    $replRows = rq($pdo, $replSql, $dt2['params'])->fetchAll();
    foreach ($replRows as $r) {
        $cost = floatval($r['delivery_cost']);
        $replacementDeliveryByOrder[$r['order_id']] = $cost;
        $replacementCountByOrder[$r['order_id']]    = intval($r['repl_count']);
        $totalReplacementsCount += intval($r['repl_count']);
        if ($r['status_id'] == 3) {
            $replacementDeliveryCost_confirmed += $cost;
        } else {
            $replacementDeliveryCost_expected  += $cost;
        }
    }
} catch (Exception $e) {}

$replacementDeliveryCost = $replacementDeliveryCost_confirmed + $replacementDeliveryCost_expected;

// ── الأرباح الإجمالية ──
$confirmed_gross_profit = ($totals['confirmed_revenue'] ?? 0) - ($totals['confirmed_cost'] ?? 0);
$expected_gross_profit  = ($totals['expected_revenue']  ?? 0) - ($totals['expected_cost']  ?? 0);

// ── الأرباح الصافية ──
$confirmed_net_profit = $confirmed_gross_profit
                      - ($totals['confirmed_delivery_paid'] ?? 0)
                      - ($totals['total_return_fees']       ?? 0)
                      - $replacementDeliveryCost_confirmed;

$expected_net_profit  = $expected_gross_profit
                      - ($totals['expected_delivery_paid']  ?? 0)
                      - $replacementDeliveryCost_expected;

// ── الخسائر ──
$confirmed_losses = ($totals['confirmed_delivery_paid'] ?? 0)
                  + ($totals['total_return_fees']       ?? 0)
                  + $replacementDeliveryCost_confirmed;

$expected_losses  = ($totals['expected_delivery_paid']  ?? 0)
                  + $replacementDeliveryCost_expected;

// ── المعدلات ──
$delivery_rate = ($totals['total_orders'] ?? 0) > 0
    ? round(($totals['delivered_orders'] ?? 0) / $totals['total_orders'] * 100, 1) : 0;
$cancel_rate = ($totals['total_orders'] ?? 0) > 0
    ? round(($totals['cancelled_orders'] ?? 0) / $totals['total_orders'] * 100, 1) : 0;

// ══════════════════════════════════════════════════════════════
//  أكثر المنتجات ربحاً — مؤكد ومتوقع
// ══════════════════════════════════════════════════════════════
$dt3 = buildDate($date_from, $date_to);
$topProductsSql = "
    SELECT p.id, p.name AS product_name, c.name AS category_name,
        SUM(oi.quantity)                                                                              AS total_quantity_sold,
        SUM(oi.quantity*oi.unit_price)                                                                AS total_revenue,
        SUM(oi.quantity*COALESCE(pv.purchase_price,0))                                               AS total_cost,
        SUM(oi.quantity*oi.unit_price)-SUM(oi.quantity*COALESCE(pv.purchase_price,0))               AS gross_profit,

        SUM(CASE WHEN o.status_id=3 THEN oi.quantity*oi.unit_price ELSE 0 END)                      AS confirmed_revenue,
        SUM(CASE WHEN o.status_id=3 THEN oi.quantity*COALESCE(pv.purchase_price,0) ELSE 0 END)      AS confirmed_cost,
        SUM(CASE WHEN o.status_id=3 THEN oi.quantity*oi.unit_price ELSE 0 END)
         - SUM(CASE WHEN o.status_id=3 THEN oi.quantity*COALESCE(pv.purchase_price,0) ELSE 0 END)   AS confirmed_profit,

        SUM(CASE WHEN o.status_id=2 THEN oi.quantity*oi.unit_price ELSE 0 END)                      AS expected_revenue,
        SUM(CASE WHEN o.status_id=2 THEN oi.quantity*COALESCE(pv.purchase_price,0) ELSE 0 END)      AS expected_cost,
        SUM(CASE WHEN o.status_id=2 THEN oi.quantity*oi.unit_price ELSE 0 END)
         - SUM(CASE WHEN o.status_id=2 THEN oi.quantity*COALESCE(pv.purchase_price,0) ELSE 0 END)   AS expected_profit,

        COUNT(DISTINCT CASE WHEN o.status_id=3 THEN o.id END)                                       AS delivered_count,
        COUNT(DISTINCT CASE WHEN o.status_id=2 THEN o.id END)                                       AS sent_count,
        COUNT(DISTINCT CASE WHEN o.status_id=4 THEN o.id END)                                       AS cancelled_count
    FROM products p
    LEFT JOIN categories c ON p.category_id=c.id
    LEFT JOIN product_variants pv ON p.id=pv.product_id
    LEFT JOIN order_items oi ON pv.id=oi.product_variant_id
    LEFT JOIN orders o ON oi.order_id=o.id
    WHERE o.status_id IN (2,3,4) {$dt3['cond']}
    GROUP BY p.id
    HAVING SUM(oi.quantity)>0
    ORDER BY confirmed_profit DESC
    LIMIT 10
";
$topProducts = rq($pdo, $topProductsSql, $dt3['params'])->fetchAll();

// ══════════════════════════════════════════════════════════════
//  الفئات
// ══════════════════════════════════════════════════════════════
$dt4 = buildDate($date_from, $date_to);
$categoriesSql = "
    SELECT c.id, c.name AS category_name,
        COUNT(DISTINCT o.id)                                                                          AS orders_count,
        SUM(oi.quantity)                                                                              AS total_quantity_sold,
        SUM(oi.quantity*oi.unit_price)                                                                AS total_revenue,
        SUM(oi.quantity*COALESCE(pv.purchase_price,0))                                               AS total_cost,
        SUM(oi.quantity*oi.unit_price)-SUM(oi.quantity*COALESCE(pv.purchase_price,0))               AS gross_profit,

        SUM(CASE WHEN o.status_id=3 THEN oi.quantity*oi.unit_price ELSE 0 END)
         - SUM(CASE WHEN o.status_id=3 THEN oi.quantity*COALESCE(pv.purchase_price,0) ELSE 0 END)   AS confirmed_profit,
        SUM(CASE WHEN o.status_id=2 THEN oi.quantity*oi.unit_price ELSE 0 END)
         - SUM(CASE WHEN o.status_id=2 THEN oi.quantity*COALESCE(pv.purchase_price,0) ELSE 0 END)   AS expected_profit,

        COUNT(DISTINCT CASE WHEN o.status_id=3 THEN o.id END)                                       AS delivered_count,
        COUNT(DISTINCT CASE WHEN o.status_id=2 THEN o.id END)                                       AS sent_count,
        COUNT(DISTINCT CASE WHEN o.status_id=4 THEN o.id END)                                       AS cancelled_count
    FROM categories c
    LEFT JOIN products p ON c.id=p.category_id
    LEFT JOIN product_variants pv ON p.id=pv.product_id
    LEFT JOIN order_items oi ON pv.id=oi.product_variant_id
    LEFT JOIN orders o ON oi.order_id=o.id
    WHERE o.status_id IN (2,3,4) {$dt4['cond']}
    GROUP BY c.id
    HAVING COUNT(DISTINCT o.id)>0
    ORDER BY confirmed_profit DESC
";
$categories = rq($pdo, $categoriesSql, $dt4['params'])->fetchAll();

// ══════════════════════════════════════════════════════════════
//  أكثر المنتجات إلغاءً
// ══════════════════════════════════════════════════════════════
$dt5 = buildDate($date_from, $date_to);
$cancelledSql = "
    SELECT p.id, p.name AS product_name, c.name AS category_name,
        COUNT(DISTINCT CASE WHEN o.status_id=4 THEN o.id END)  AS cancelled_orders,
        SUM(CASE WHEN o.status_id=4 THEN oi.quantity ELSE 0 END) AS cancelled_quantity,
        SUM(CASE WHEN o.status_id=4 THEN oi.quantity*COALESCE(pv.purchase_price,0) ELSE 0 END) AS cancelled_cost,
        COUNT(DISTINCT CASE WHEN o.status_id=3 THEN o.id END)  AS delivered_orders,
        COUNT(DISTINCT CASE WHEN o.status_id=2 THEN o.id END)  AS sent_orders,
        ROUND(
            COUNT(DISTINCT CASE WHEN o.status_id=4 THEN o.id END)*100.0
            /NULLIF(COUNT(DISTINCT o.id),0),1
        ) AS cancellation_rate
    FROM products p
    LEFT JOIN categories c ON p.category_id=c.id
    LEFT JOIN product_variants pv ON p.id=pv.product_id
    LEFT JOIN order_items oi ON pv.id=oi.product_variant_id
    LEFT JOIN orders o ON oi.order_id=o.id
    WHERE o.status_id IN (2,3,4) {$dt5['cond']}
    GROUP BY p.id
    HAVING cancelled_orders>0
    ORDER BY cancelled_orders DESC
    LIMIT 10
";
$mostCancelled = rq($pdo, $cancelledSql, $dt5['params'])->fetchAll();

// ══════════════════════════════════════════════════════════════
//  شركات التوصيل
// ══════════════════════════════════════════════════════════════
$deliveryCond = ''; $deliveryParams = [];
if (!empty($date_from) && !empty($date_to))    { $deliveryCond = " AND DATE(o.order_date) BETWEEN ? AND ?"; $deliveryParams = [$date_from, $date_to]; }
elseif (!empty($date_from))                    { $deliveryCond = " AND DATE(o.order_date) >= ?";            $deliveryParams = [$date_from]; }
elseif (!empty($date_to))                      { $deliveryCond = " AND DATE(o.order_date) <= ?";            $deliveryParams = [$date_to]; }

$deliverySql = "
    SELECT dc.id, dc.name AS company_name, COALESCE(dc.return_fee,200) AS return_fee,
        COUNT(DISTINCT CASE WHEN o.status_id=3 THEN o.id END) AS delivered_orders,
        COUNT(DISTINCT CASE WHEN o.status_id=2 THEN o.id END) AS sent_orders,
        COUNT(DISTINCT CASE WHEN o.status_id=4 THEN o.id END) AS cancelled_orders,
        COUNT(DISTINCT CASE WHEN o.status_id=4 THEN o.id END)*COALESCE(dc.return_fee,200) AS total_return_fees
    FROM delivery_companies dc
    JOIN orders o ON dc.id=o.delivery_company_id
    WHERE o.status_id IN (2,3,4) {$deliveryCond}
    GROUP BY dc.id
    HAVING (COUNT(DISTINCT CASE WHEN o.status_id=3 THEN o.id END)+COUNT(DISTINCT CASE WHEN o.status_id=2 THEN o.id END)+COUNT(DISTINCT CASE WHEN o.status_id=4 THEN o.id END))>0
    ORDER BY cancelled_orders DESC
";
$deliveryStats = rq($pdo, $deliverySql, $deliveryParams)->fetchAll();

// ══════════════════════════════════════════════════════════════
//  آخر 50 طلب
// ══════════════════════════════════════════════════════════════
$dt7 = buildDate($date_from, $date_to);
$lastOrdersSql = "
    SELECT o.id, o.customer_name, o.order_date, o.status_id,
        o.delivery_company_id, o.wilaya_id, o.delivery_type, o.delivery_price_modified,
        os.name AS status_name, dc.name AS delivery_company_name, w.name AS wilaya_name
    FROM orders o
    LEFT JOIN order_statuses os ON o.status_id=os.id
    LEFT JOIN delivery_companies dc ON o.delivery_company_id=dc.id
    LEFT JOIN wilayas w ON o.wilaya_id=w.id
    WHERE 1=1 {$dt7['cond']}
    ORDER BY o.order_date DESC
    LIMIT 50
";
$lastOrders = rq($pdo, $lastOrdersSql, $dt7['params'])->fetchAll();

$orderTotals = [];
foreach ($lastOrders as $order) {
    $oid = $order['id'];
    try {
        $items = rq($pdo,
            "SELECT oi.quantity, oi.unit_price, COALESCE(pv.purchase_price,0) AS purchase_price
             FROM order_items oi LEFT JOIN product_variants pv ON oi.product_variant_id=pv.id
             WHERE oi.order_id=?", [$oid]
        )->fetchAll();
    } catch (Exception $e) { $items = []; }

    $selling = 0; $purchase = 0;
    foreach ($items as $item) {
        $selling  += $item['quantity'] * $item['unit_price'];
        $purchase += $item['quantity'] * $item['purchase_price'];
    }

    if ($order['delivery_price_modified'] !== null && $order['delivery_price_modified'] !== '') {
        $deliveryPrice = floatval($order['delivery_price_modified']);
    } else {
        try {
            $dp = rq($pdo,
                "SELECT price FROM delivery_prices WHERE wilaya_id=? AND delivery_type=? AND delivery_company_id=? LIMIT 1",
                [$order['wilaya_id'], $order['delivery_type'], $order['delivery_company_id']]
            )->fetchColumn();
            $deliveryPrice = floatval($dp ?: 0);
        } catch (Exception $e) { $deliveryPrice = 0; }
    }

    $replDelivery = $replacementDeliveryByOrder[$oid] ?? 0;
    $replCount    = $replacementCountByOrder[$oid]    ?? 0;

    // تحديد نوع الطلب
    $isConfirmed = ($order['status_id'] == 3);
    $isExpected  = ($order['status_id'] == 2);
    $isCancelled = ($order['status_id'] == 4);

    if ($isCancelled) {
        $returnFee     = $return_fees[$order['delivery_company_id']] ?? 200;
        $profit        = -$returnFee;
        $deliveryPrice = 0;
        $replDelivery  = 0;
        $profit_type   = 'loss';
    } elseif ($isConfirmed) {
        $profit      = $selling - $purchase - $deliveryPrice - $replDelivery;
        $profit_type = 'confirmed';
    } else {
        // مرسلة = متوقعة
        $profit      = $selling - $purchase - $deliveryPrice - $replDelivery;
        $profit_type = 'expected';
    }

    $orderTotals[$oid] = [
        'selling'       => $selling,
        'purchase'      => $purchase,
        'delivery'      => $deliveryPrice,
        'repl_delivery' => $replDelivery,
        'repl_count'    => $replCount,
        'profit'        => $profit,
        'profit_type'   => $profit_type,
    ];
}

$periodLabel = match($period) {
    'today'  => 'اليوم — ' . $today,
    'week'   => 'آخر 7 أيام',
    'month'  => 'الشهر — ' . date('Y/m'),
    'year'   => 'السنة — '  . date('Y'),
    'custom' => (!empty($date_from)||!empty($date_to)) ? ($date_from . ' → ' . $date_to) : 'مخصص',
    default  => 'كل الفترات',
};
?>
<!DOCTYPE html>
<html dir="rtl" lang="ar" data-theme="light">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<title>الأرباح والخسائر</title>
<link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;700;800;900&family=IBM+Plex+Mono:wght@400;600&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<style>
:root{
    --bg:#F0F4FA;--bg2:#E8EDF7;--surf:#FFF;--surf2:#F8FAFF;--surf3:#EFF3FC;
    --bdr:#DDE3F0;--bdr2:#C8D2E8;
    --ink:#0C1229;--ink2:#1E2D52;--ink3:#3A4A72;--mut:#7A8AAE;--mut2:#A0AECA;
    --blue:#1D4ED8;--bluel:#EEF3FF;--bluesat:#3B82F6;--blued:#1E3A8A;
    --green:#047857;--greenl:#ECFDF5;--greensat:#10B981;
    --amber:#B45309;--amberl:#FFFBEB;--ambersat:#F59E0B;
    --red:#B91C1C;--redl:#FEF2F2;--redsat:#EF4444;
    --purple:#5B21B6;--purpl:#F5F3FF;--purpsat:#8B5CF6;
    --teal:#0F766E;--teall:#F0FDFA;--tealsat:#14B8A6;
    --rose:#9F1239;--rosel:#FFF1F2;--rosesat:#F43F5E;
    /* ألوان جديدة للمتوقع */
    --exp:#7C3AED;--expl:#F5F3FF;--expsat:#8B5CF6;--expd:#5B21B6;
    --shsm:0 1px 4px rgba(12,18,41,.06);--sh:0 3px 14px rgba(12,18,41,.08);
    --shmd:0 8px 32px rgba(12,18,41,.10);--shlg:0 20px 60px rgba(12,18,41,.14);
    --r:18px;--rsm:10px;--rxs:6px;--tr:all .22s cubic-bezier(.4,0,.2,1);
}
[data-theme="dark"]{
    --bg:#0B0F1E;--bg2:#111827;--surf:#161D30;--surf2:#1C2540;--surf3:#232D4A;
    --bdr:#2A3554;--bdr2:#354070;
    --ink:#E8EEFF;--ink2:#C0CCEE;--ink3:#8896C0;--mut:#5A6888;--mut2:#3D4E70;
    --bluel:#0F1E40;--greenl:#052E1E;--amberl:#2A1A00;--redl:#2D0A0A;
    --purpl:#1A0E3A;--teall:#061E1A;--rosel:#2D0812;--expl:#1E1040;
    --shsm:0 1px 4px rgba(0,0,0,.3);--sh:0 3px 14px rgba(0,0,0,.4);
    --shmd:0 8px 32px rgba(0,0,0,.5);--shlg:0 20px 60px rgba(0,0,0,.6);
}
*,*::before,*::after{margin:0;padding:0;box-sizing:border-box}
html{scroll-behavior:smooth}
body{font-family:'Tajawal',sans-serif;background:var(--bg);color:var(--ink);min-height:100vh;padding:20px;transition:background .3s,color .3s;line-height:1.5}
::-webkit-scrollbar{width:5px;height:5px}
::-webkit-scrollbar-track{background:var(--bg2)}
::-webkit-scrollbar-thumb{background:var(--bluesat);border-radius:10px}
.container{max-width:1680px;margin:0 auto}

/* ══ DARK TOGGLE ══ */
.dm-toggle{position:fixed;top:72px;right:15px;z-index:800;width:44px;height:44px;border-radius:50%;background:var(--surf);border:2px solid var(--bdr);box-shadow:var(--shmd);cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:20px;transition:var(--tr);color:var(--ink)}
.dm-toggle:hover{transform:scale(1.12) rotate(22deg);box-shadow:var(--shlg);border-color:var(--bluesat)}

/* ══ HEADER ══ */
.page-header{background:linear-gradient(135deg,var(--ink) 0%,var(--ink2) 55%,#1A3480 100%);border-radius:var(--r);padding:24px 28px;margin-bottom:18px;display:flex;justify-content:space-between;align-items:center;position:relative;overflow:hidden;animation:fadeDown .5s ease both;flex-wrap:wrap;gap:14px;box-shadow:var(--shlg)}
.page-header::before{content:'';position:absolute;top:-80px;left:-80px;width:280px;height:280px;border-radius:50%;background:radial-gradient(circle,rgba(59,130,246,.18) 0%,transparent 70%);pointer-events:none}
.page-header::after{content:'';position:absolute;bottom:-60px;right:5%;width:220px;height:220px;border-radius:50%;background:radial-gradient(circle,rgba(139,92,246,.14) 0%,transparent 70%);pointer-events:none}
@keyframes fadeDown{from{opacity:0;transform:translateY(-16px)}to{opacity:1;transform:translateY(0)}}
@keyframes fadeUp{from{opacity:0;transform:translateY(16px)}to{opacity:1;transform:translateY(0)}}
.header-left h1{font-size:22px;font-weight:900;color:#fff;display:flex;align-items:center;gap:10px;margin-bottom:5px;position:relative;z-index:1}
.pulse-dot{width:10px;height:10px;border-radius:50%;background:#34D399;display:inline-block;animation:ping 1.8s ease-in-out infinite;flex-shrink:0}
@keyframes ping{0%{box-shadow:0 0 0 0 rgba(52,211,153,.6)}70%{box-shadow:0 0 0 10px rgba(52,211,153,0)}100%{box-shadow:0 0 0 0 rgba(52,211,153,0)}}
.header-sub{color:rgba(255,255,255,.5);font-size:12px;font-weight:500;position:relative;z-index:1}
.period-badge{background:rgba(255,255,255,.15);backdrop-filter:blur(8px);border:1px solid rgba(255,255,255,.2);border-radius:20px;padding:5px 14px;font-size:12px;font-weight:700;color:rgba(255,255,255,.9);display:inline-flex;align-items:center;gap:6px;margin-top:6px}
.header-right{display:flex;gap:8px;position:relative;z-index:2;flex-wrap:wrap}

/* ══ LEGEND BANNER ══ */
.legend-banner{background:var(--surf);border-radius:var(--r);padding:14px 20px;border:1px solid var(--bdr);box-shadow:var(--sh);margin-bottom:18px;display:flex;gap:20px;flex-wrap:wrap;align-items:center;animation:fadeUp .35s ease both}
.legend-banner .lb-title{font-size:12px;font-weight:800;color:var(--mut);text-transform:uppercase;letter-spacing:.6px;margin-left:4px}
.legend-item{display:flex;align-items:center;gap:7px;font-size:13px;font-weight:700}
.li-dot{width:11px;height:11px;border-radius:3px;flex-shrink:0}
.li-dot.confirmed{background:var(--greensat)}
.li-dot.expected{background:var(--expsat)}
.li-dot.loss{background:var(--redsat)}

/* ══ FILTER ══ */
.filter-bar{background:var(--surf);border-radius:var(--r);padding:16px 20px;border:1px solid var(--bdr);box-shadow:var(--sh);margin-bottom:18px;animation:fadeUp .4s ease .05s both;transition:background .3s,border-color .3s}
.filter-bar-title{font-size:11px;font-weight:800;color:var(--mut);text-transform:uppercase;letter-spacing:.8px;margin-bottom:10px;display:flex;align-items:center;gap:6px}
.period-row{display:flex;flex-wrap:wrap;gap:6px;align-items:center}
.period-btn{padding:7px 16px;border-radius:20px;border:1.5px solid var(--bdr);background:var(--surf2);color:var(--mut);font-size:13px;font-weight:700;cursor:pointer;transition:var(--tr);text-decoration:none;display:inline-block;font-family:'Tajawal',sans-serif}
.period-btn:hover{border-color:var(--bluesat);color:var(--blue);background:var(--bluel)}
.period-btn.active{background:var(--blue);color:white;border-color:var(--blue);box-shadow:0 4px 14px rgba(30,64,175,.35)}
.custom-dates{display:flex;gap:10px;align-items:center;flex-wrap:wrap;padding-top:12px;margin-top:10px;border-top:1px solid var(--bdr)}
.custom-dates input[type="date"]{padding:9px 13px;border:1.5px solid var(--bdr);border-radius:var(--rsm);font-size:13px;color:var(--ink);font-family:'Tajawal',sans-serif;background:var(--surf2);outline:none;transition:var(--tr)}
.custom-dates input:focus{border-color:var(--bluesat);box-shadow:0 0 0 3px rgba(59,130,246,.12)}
.custom-dates label{font-size:12px;font-weight:700;color:var(--mut)}

/* ══ KPI DOUBLE GRID ══ */
.kpi-section-label{font-size:11px;font-weight:900;letter-spacing:.8px;text-transform:uppercase;padding:6px 14px;border-radius:20px;display:inline-flex;align-items:center;gap:6px;margin-bottom:12px}
.ksl-confirmed{background:var(--greenl);color:var(--green)}
.ksl-expected{background:var(--expl);color:var(--exp)}

.kpi-pair-wrap{margin-bottom:18px;animation:fadeUp .45s ease .1s both}
.kpi-pair-header{display:flex;align-items:center;gap:12px;margin-bottom:10px;flex-wrap:wrap}
.kpi-pair-divider{flex:1;height:1px;background:var(--bdr)}

.kpi-grid{display:grid;grid-template-columns:repeat(5,1fr);gap:12px;margin-bottom:12px}
@media(max-width:1200px){.kpi-grid{grid-template-columns:repeat(3,1fr)}}
@media(max-width:700px){.kpi-grid{grid-template-columns:repeat(2,1fr)}}
@media(max-width:420px){.kpi-grid{grid-template-columns:1fr}}

.kpi{background:var(--surf);border-radius:var(--r);padding:16px 18px 14px;border:1px solid var(--bdr);box-shadow:var(--sh);transition:var(--tr);position:relative;overflow:hidden}
.kpi::before{content:'';position:absolute;top:0;right:0;width:5px;height:100%;border-radius:0 var(--r) var(--r) 0;transition:width .3s}
.kpi:hover{transform:translateY(-4px);box-shadow:var(--shmd)}
.kpi:hover::before{width:7px}

/* confirmed = green accent */
.kpi.k-conf-blue::before{background:linear-gradient(180deg,var(--bluesat),var(--blued))}
.kpi.k-conf-green::before{background:linear-gradient(180deg,var(--greensat),var(--green))}
.kpi.k-conf-teal::before{background:linear-gradient(180deg,var(--tealsat),var(--teal))}
.kpi.k-conf-purple::before{background:linear-gradient(180deg,var(--greensat),var(--green))}
.kpi.k-conf-red::before{background:linear-gradient(180deg,var(--redsat),var(--red))}

/* expected = purple accent */
.kpi.k-exp-blue::before{background:linear-gradient(180deg,var(--expsat),var(--expd))}
.kpi.k-exp-green::before{background:linear-gradient(180deg,var(--expsat),var(--expd))}
.kpi.k-exp-teal::before{background:linear-gradient(180deg,var(--expsat),var(--expd))}
.kpi.k-exp-purple::before{background:linear-gradient(180deg,var(--expsat),var(--expd))}
.kpi.k-exp-red::before{background:linear-gradient(180deg,var(--expsat),var(--expd))}

/* confirmed border glow */
.kpi.confirmed-kpi{border-color:rgba(16,185,129,.25)}
/* expected border glow */
.kpi.expected-kpi{border-color:rgba(139,92,246,.22);background:var(--surf)}

.kpi-top{display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:10px}
.kpi-icon{width:40px;height:40px;border-radius:11px;display:flex;align-items:center;justify-content:center;font-size:21px;flex-shrink:0}
.kpi-trend{font-size:11px;font-weight:800;padding:3px 8px;border-radius:20px;display:inline-flex;align-items:center;gap:3px}
.kpi-val{font-size:24px;font-weight:900;color:var(--ink);letter-spacing:-0.5px;line-height:1;font-family:'IBM Plex Mono',monospace;margin-bottom:4px}
.kpi-val.pos{color:var(--green)}
.kpi-val.neg{color:var(--red)}
.kpi-val.exp{color:var(--exp)}
.kpi-lbl{font-size:11px;color:var(--mut);font-weight:700;text-transform:uppercase;letter-spacing:.4px}
.kpi-sub{font-size:11px;color:var(--mut2);margin-top:4px;line-height:1.5}

/* tag الصغير في كل KPI */
.kpi-type-tag{position:absolute;top:12px;left:12px;font-size:9px;font-weight:900;letter-spacing:.5px;padding:2px 7px;border-radius:10px;text-transform:uppercase}
.ktt-confirmed{background:var(--greenl);color:var(--green)}
.ktt-expected{background:var(--expl);color:var(--exp)}

/* ══ RATE CARDS ══ */
.rate-row{display:flex;gap:12px;flex-wrap:wrap;margin-bottom:18px;animation:fadeUp .45s ease .13s both}
.rate-card{flex:1;min-width:160px;background:var(--surf);border-radius:var(--r);padding:16px 18px;border:1px solid var(--bdr);box-shadow:var(--sh);display:flex;align-items:center;gap:14px;transition:var(--tr)}
.rate-card:hover{transform:translateY(-2px);box-shadow:var(--shmd)}
.rate-ring{width:52px;height:52px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:10px;font-weight:900;font-family:'IBM Plex Mono',monospace;flex-shrink:0;border:2.5px solid;text-align:center;line-height:1.2}
.rate-ring.green{background:var(--greenl);color:var(--green);border-color:var(--greensat)}
.rate-ring.red{background:var(--redl);color:var(--red);border-color:var(--redsat)}
.rate-ring.blue{background:var(--bluel);color:var(--blue);border-color:var(--bluesat)}
.rate-ring.amber{background:var(--amberl);color:var(--amber);border-color:var(--ambersat)}
.rate-ring.rose{background:var(--rosel);color:var(--rose);border-color:var(--rosesat)}
.rate-ring.exp{background:var(--expl);color:var(--exp);border-color:var(--expsat)}
.rate-info b{display:block;font-size:13px;font-weight:800;color:var(--ink);margin-bottom:3px}
.rate-info small{font-size:11px;color:var(--mut);line-height:1.5}

/* ══ SECTION TITLE ══ */
.section-title{font-size:14px;font-weight:800;color:var(--ink);margin-bottom:14px;display:flex;align-items:center;gap:8px}
.sti{width:28px;height:28px;border-radius:8px;background:var(--bluel);display:flex;align-items:center;justify-content:center;font-size:15px;flex-shrink:0}

/* ══ CHARTS ══ */
.charts-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:14px;margin-bottom:18px;animation:fadeUp .45s ease .18s both}
@media(max-width:900px){.charts-grid{grid-template-columns:1fr}}
.chart-card{background:var(--surf);border-radius:var(--r);padding:20px;box-shadow:var(--sh);border:1px solid var(--bdr);transition:background .3s,border-color .3s}
.chart-card:hover{box-shadow:var(--shmd)}
.chart-container{height:230px;position:relative}
.chart-empty{display:flex;align-items:center;justify-content:center;height:100%;flex-direction:column;gap:10px;color:var(--mut);font-size:13px;font-weight:600}
.chart-empty .ce{font-size:36px}

/* ══ PRODUCT CARDS ══ */
.prod-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:14px;margin-bottom:18px;animation:fadeUp .45s ease .22s both}
@media(max-width:600px){.prod-grid{grid-template-columns:1fr}}
.prod-card{background:var(--surf);border-radius:var(--r);border:1px solid var(--bdr);box-shadow:var(--sh);overflow:hidden;transition:var(--tr)}
.prod-card:hover{transform:translateY(-3px);box-shadow:var(--shmd);border-color:var(--bluesat)}
.pc-header{padding:14px 16px 10px;display:flex;align-items:center;gap:10px}
.pc-rank{width:30px;height:30px;border-radius:9px;display:flex;align-items:center;justify-content:center;font-size:13px;font-weight:900;flex-shrink:0}
.pc-rank.gold{background:linear-gradient(135deg,#FEF3C7,#FDE68A);color:#92400E}
.pc-rank.silver{background:linear-gradient(135deg,#F1F5F9,#E2E8F0);color:#64748B}
.pc-rank.bronze{background:linear-gradient(135deg,#FEF3C7,#FCD9A0);color:#A16207}
.pc-rank.normal{background:var(--surf2);color:var(--mut);border:1px solid var(--bdr)}
.pc-name{flex:1;font-size:13px;font-weight:800;color:var(--ink);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.pc-cat{font-size:10px;color:var(--mut);margin-top:2px}
.pc-body{padding:0 16px 12px;display:grid;grid-template-columns:1fr 1fr;gap:7px}
.pc-stat{background:var(--surf2);border-radius:var(--rsm);padding:8px 10px;border:1px solid var(--bdr);transition:background .3s}
.pc-stat.confirmed-stat{border-color:rgba(16,185,129,.3);background:rgba(16,185,129,.04)}
.pc-stat.expected-stat{border-color:rgba(139,92,246,.3);background:rgba(139,92,246,.04)}
.pc-stat-lbl{font-size:10px;color:var(--mut);font-weight:700;text-transform:uppercase;letter-spacing:.3px;margin-bottom:3px}
.pc-stat-val{font-size:14px;font-weight:900;color:var(--ink);font-family:'IBM Plex Mono',monospace}
.pc-stat-val.pos{color:var(--green)}
.pc-stat-val.exp{color:var(--exp)}
.pc-stat-val.neg{color:var(--red)}
.pc-bar-wrap{padding:0 16px 14px}
.pc-bar-lbl{display:flex;justify-content:space-between;font-size:11px;color:var(--mut);font-weight:700;margin-bottom:5px}
.pc-bar{height:7px;background:var(--bg2);border-radius:10px;overflow:hidden;display:flex}
.pc-bar-fill{height:100%;border-radius:10px 0 0 10px;transition:width .9s cubic-bezier(.4,0,.2,1)}
.pc-bar-fill2{height:100%;transition:width .9s cubic-bezier(.4,0,.2,1)}
.fg{background:linear-gradient(90deg,var(--greensat),#34D399)}
.fexp{background:linear-gradient(90deg,var(--expsat),#A78BFA)}
.fa{background:linear-gradient(90deg,var(--ambersat),#FCD34D)}
.fr{background:linear-gradient(90deg,var(--redsat),#FC8181)}
.fb{background:linear-gradient(90deg,var(--bluesat),#93C5FD)}

/* ══ TABLE ══ */
.table-wrap{background:var(--surf);border-radius:var(--r);padding:20px;box-shadow:var(--sh);border:1px solid var(--bdr);margin-bottom:18px;animation:fadeUp .45s ease .28s both;transition:background .3s,border-color .3s;overflow:hidden}
.table-scroll{overflow-x:auto;border-radius:var(--rsm);border:1px solid var(--bdr);-webkit-overflow-scrolling:touch}
.dt{width:100%;border-collapse:collapse;font-size:13px;min-width:600px}
.dt th{background:linear-gradient(135deg,var(--ink),var(--ink2));color:white;padding:12px 13px;text-align:right;font-weight:700;font-size:12px;white-space:nowrap}
.dt td{padding:11px 13px;border-bottom:1px solid var(--bdr);color:var(--ink3);vertical-align:middle}
.dt tr:last-child td{border-bottom:none}
.dt tr{transition:var(--tr)}
.dt tr:hover td{background:var(--surf3)}
.dt td:first-child{font-weight:700;color:var(--ink);font-family:'IBM Plex Mono',monospace}
.profit-pos{color:var(--green);font-weight:800;font-family:'IBM Plex Mono',monospace}
.profit-exp{color:var(--exp);font-weight:800;font-family:'IBM Plex Mono',monospace}
.profit-neg{color:var(--red);font-weight:800;font-family:'IBM Plex Mono',monospace}
.mono{font-family:'IBM Plex Mono',monospace;font-weight:600}
.badge{padding:4px 10px;border-radius:20px;font-size:11px;font-weight:800;display:inline-flex;align-items:center;gap:4px;white-space:nowrap}
.b-success{background:var(--greenl);color:var(--green)}
.b-danger{background:var(--redl);color:var(--red)}
.b-warning{background:var(--amberl);color:var(--amber)}
.b-info{background:var(--bluel);color:var(--blue)}
.b-expected{background:var(--expl);color:var(--exp)}
.repl-hl td{background:rgba(139,92,246,.04)!important}
.repl-badge{background:var(--purpl);color:var(--purple);border:1px solid var(--purpsat);padding:2px 8px;border-radius:8px;font-size:10px;font-weight:800;display:inline-flex;align-items:center;gap:3px}

/* ── سطر الطلبات المرسلة ── */
.dt tr.row-expected td{background:rgba(139,92,246,.03)}
.dt tr.row-expected:hover td{background:rgba(139,92,246,.07)}
.dt tr.row-confirmed td{background:rgba(16,185,129,.02)}
.dt tr.row-confirmed:hover td{background:rgba(16,185,129,.06)}

/* ══ DELIVERY COMPANIES ══ */
.dc-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:12px;margin-bottom:18px;animation:fadeUp .45s ease .25s both}
.dc-card{background:var(--surf);border-radius:var(--r);padding:18px;border:1px solid var(--bdr);box-shadow:var(--sh);transition:var(--tr)}
.dc-card:hover{transform:translateY(-3px);box-shadow:var(--shmd);border-color:var(--bluesat)}
.dc-name{font-size:14px;font-weight:800;color:var(--ink);margin-bottom:12px;display:flex;align-items:center;gap:7px}
.dc-stats{display:flex;flex-direction:column;gap:7px}
.dc-row{display:flex;justify-content:space-between;align-items:center;font-size:12px}
.dc-row-lbl{color:var(--mut);font-weight:600}
.dc-row-val{font-weight:800;font-family:'IBM Plex Mono',monospace;color:var(--ink)}
.dc-div{height:1px;background:var(--bdr);margin:4px 0}

/* ══ BUTTONS ══ */
.btn{padding:9px 16px;border-radius:var(--rsm);font-family:'Tajawal',sans-serif;font-weight:700;cursor:pointer;transition:var(--tr);text-decoration:none;display:inline-flex;align-items:center;gap:6px;font-size:13px;border:none;white-space:nowrap}
.btn-primary{background:var(--blue);color:white}
.btn-primary:hover{background:var(--blued);transform:translateY(-1px);box-shadow:0 4px 14px rgba(30,64,175,.35)}
.btn-ghost{background:rgba(255,255,255,.12);color:#fff;border:1px solid rgba(255,255,255,.22);backdrop-filter:blur(8px)}
.btn-ghost:hover{background:rgba(255,255,255,.22);transform:translateY(-1px)}

/* ══ PROGRESS ══ */
.prog-wrap{height:5px;background:var(--bdr);border-radius:10px;overflow:hidden;margin-top:5px}
.prog-fill{height:100%;border-radius:10px;transition:width .9s cubic-bezier(.4,0,.2,1)}
.prog-green{background:linear-gradient(90deg,var(--greensat),#34D399)}
.prog-red{background:linear-gradient(90deg,var(--redsat),#FC8181)}

/* ══ ALERT ══ */
.info-alert{background:var(--purpl);border:1.5px solid var(--purpsat);border-radius:var(--rsm);padding:12px 16px;margin-bottom:14px;font-size:13px;color:var(--purple);font-weight:600;display:flex;align-items:center;gap:10px}

/* ══ SUMMARY BOX ══ */
.summary-box{background:var(--surf);border-radius:var(--r);padding:20px 24px;border:1px solid var(--bdr);box-shadow:var(--sh);margin-bottom:18px;animation:fadeUp .45s ease .08s both}
.sb-row{display:flex;justify-content:space-between;align-items:center;padding:10px 0;border-bottom:1px solid var(--bdr)}
.sb-row:last-child{border-bottom:none}
.sb-lbl{font-size:13px;font-weight:700;color:var(--ink3);display:flex;align-items:center;gap:8px}
.sb-vals{display:flex;gap:20px}
.sb-val{text-align:left}
.sb-val-num{font-size:15px;font-weight:900;font-family:'IBM Plex Mono',monospace}
.sb-val-tag{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.4px}
.sv-confirmed .sb-val-num{color:var(--green)}
.sv-confirmed .sb-val-tag{color:var(--greensat)}
.sv-expected .sb-val-num{color:var(--exp)}
.sv-expected .sb-val-tag{color:var(--expsat)}
.sv-neg .sb-val-num{color:var(--red)}
.sv-neg .sb-val-tag{color:var(--redsat)}

@media(max-width:600px){body{padding:12px 10px}.page-header{padding:16px 18px}.header-left h1{font-size:17px}.kpi-val{font-size:20px}.rate-card{min-width:140px}.sb-vals{gap:12px}.sb-val-num{font-size:13px}}
@media print{.filter-bar,.header-right,.dm-toggle,.sidebar-overlay{display:none!important}body{background:white;padding:0;color:black}.page-header{background:#1E2840!important;-webkit-print-color-adjust:exact}}
</style>
</head>
<body>

<button class="dm-toggle" id="dmToggle" title="وضع ليلي" onclick="toggleDark()">🌙</button>

<button onclick="toggleSidebar()" style="position:fixed;top:15px;right:15px;z-index:900;background:var(--ink);color:white;border:none;padding:10px 13px;border-radius:var(--rsm);cursor:pointer;display:flex;align-items:center;box-shadow:var(--shmd)">
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round">
        <line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/>
    </svg>
</button>
<div class="sidebar-overlay" onclick="toggleSidebar()"></div>
<?php include 'sidebar.php'; ?>

<div class="container">

<!-- HEADER -->
<div class="page-header">
    <div class="header-left">
        <h1><span class="pulse-dot"></span> 📊 الأرباح والخسائر</h1>
        <div class="header-sub">أرباح مؤكدة (مسلّمة) — أرباح متوقعة (مرسلة) — إحصاءات الإلغاء</div>
        <div class="period-badge">📅 <?= htmlspecialchars($periodLabel) ?></div>
    </div>
    <div class="header-right">
        <button onclick="window.print()" class="btn btn-ghost">
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
                <polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 01-2-2v-5a2 2 0 012-2h16a2 2 0 012 2v5a2 2 0 01-2 2h-2"/><rect x="6" y="14" width="12" height="8"/>
            </svg>
            طباعة
        </button>
        <a href="orders.php" class="btn btn-ghost">← الطلبات</a>
    </div>
</div>

<!-- LEGEND -->
<div class="legend-banner">
    <span class="lb-title">دليل الألوان:</span>
    <div class="legend-item"><span class="li-dot confirmed"></span><span style="color:var(--green)">أرباح مؤكدة</span> — طلبات تم استلامها فعلياً ✅</div>
    <div class="legend-item"><span class="li-dot expected"></span><span style="color:var(--exp)">أرباح متوقعة</span> — طلبات مرسلة لم تُستلم بعد 🚚</div>
    <div class="legend-item"><span class="li-dot loss"></span><span style="color:var(--red)">خسارة</span> — طلبات ملغاة ❌</div>
</div>

<!-- FILTER -->
<div class="filter-bar">
    <div class="filter-bar-title">🔽 فلترة الفترة الزمنية</div>
    <form method="GET" id="filterForm">
        <div class="period-row">
            <?php foreach(['all'=>['📋','الكل'],'today'=>['📅','اليوم'],'week'=>['🗓️','7 أيام'],'month'=>['📆','الشهر'],'year'=>['🗃️','السنة'],'custom'=>['🔧','مخصص']] as $k=>[$ic,$lbl]): ?>
            <button type="submit" name="period" value="<?=$k?>" class="period-btn <?=$period===$k?'active':''?>"><?=$ic?> <?=$lbl?></button>
            <?php endforeach; ?>
        </div>
        <?php if($period==='custom'): ?>
        <div class="custom-dates">
            <label>من:</label>
            <input type="date" name="date_from" value="<?=htmlspecialchars($date_from)?>">
            <span style="color:var(--mut)">→</span>
            <label>إلى:</label>
            <input type="date" name="date_to" value="<?=htmlspecialchars($date_to)?>">
            <input type="hidden" name="period" value="custom">
            <button type="submit" class="btn btn-primary" style="padding:8px 16px">تطبيق ✓</button>
        </div>
        <?php else: ?>
        <input type="hidden" name="date_from" value="<?=htmlspecialchars($date_from)?>">
        <input type="hidden" name="date_to"   value="<?=htmlspecialchars($date_to)?>">
        <?php endif; ?>
    </form>
</div>

<!-- ══ SUMMARY BOX ══ -->
<div class="summary-box">
    <div class="section-title" style="margin-bottom:14px"><div class="sti">💡</div>ملخص مالي سريع — <?=htmlspecialchars($periodLabel)?></div>
    <div class="sb-row">
        <div class="sb-lbl">🛒 الطلبات</div>
        <div class="sb-vals">
            <div class="sb-val sv-confirmed">
                <div class="sb-val-num"><?=$totals['delivered_orders']??0?></div>
                <div class="sb-val-tag">✅ مؤكدة</div>
            </div>
            <div class="sb-val sv-expected">
                <div class="sb-val-num"><?=$totals['sent_orders']??0?></div>
                <div class="sb-val-tag">🚚 متوقعة</div>
            </div>
            <div class="sb-val sv-neg">
                <div class="sb-val-num"><?=$totals['cancelled_orders']??0?></div>
                <div class="sb-val-tag">❌ ملغاة</div>
            </div>
        </div>
    </div>
    <div class="sb-row">
        <div class="sb-lbl">💰 الإيرادات (دج)</div>
        <div class="sb-vals">
            <div class="sb-val sv-confirmed">
                <div class="sb-val-num"><?=number_format($totals['confirmed_revenue']??0,0)?></div>
                <div class="sb-val-tag">✅ مؤكدة</div>
            </div>
            <div class="sb-val sv-expected">
                <div class="sb-val-num"><?=number_format($totals['expected_revenue']??0,0)?></div>
                <div class="sb-val-tag">🚚 متوقعة</div>
            </div>
        </div>
    </div>
    <div class="sb-row">
        <div class="sb-lbl">📈 الربح الإجمالي (دج)</div>
        <div class="sb-vals">
            <div class="sb-val sv-confirmed">
                <div class="sb-val-num"><?=number_format($confirmed_gross_profit,0)?></div>
                <div class="sb-val-tag">✅ مؤكد</div>
            </div>
            <div class="sb-val sv-expected">
                <div class="sb-val-num"><?=number_format($expected_gross_profit,0)?></div>
                <div class="sb-val-tag">🚚 متوقع</div>
            </div>
        </div>
    </div>
    <div class="sb-row">
        <div class="sb-lbl">🚚 تكلفة التوصيل (دج)</div>
        <div class="sb-vals">
            <div class="sb-val sv-neg">
                <div class="sb-val-num"><?=number_format($totals['confirmed_delivery_paid']??0,0)?></div>
                <div class="sb-val-tag">✅ مؤكدة</div>
            </div>
            <div class="sb-val sv-expected">
                <div class="sb-val-num"><?=number_format($totals['expected_delivery_paid']??0,0)?></div>
                <div class="sb-val-tag">🚚 متوقعة</div>
            </div>
        </div>
    </div>
    <?php if(($totals['total_return_fees']??0)>0): ?>
    <div class="sb-row">
        <div class="sb-lbl">↩️ رسوم الإرجاع (دج)</div>
        <div class="sb-vals">
            <div class="sb-val sv-neg">
                <div class="sb-val-num"><?=number_format($totals['total_return_fees']??0,0)?></div>
                <div class="sb-val-tag">❌ خسارة</div>
            </div>
        </div>
    </div>
    <?php endif; ?>
    <?php if($replacementDeliveryCost>0): ?>
    <div class="sb-row">
        <div class="sb-lbl">🔄 توصيل الاستبدالات (دج)</div>
        <div class="sb-vals">
            <div class="sb-val sv-neg">
                <div class="sb-val-num"><?=number_format($replacementDeliveryCost_confirmed,0)?></div>
                <div class="sb-val-tag">✅ مؤكدة</div>
            </div>
            <div class="sb-val sv-expected">
                <div class="sb-val-num"><?=number_format($replacementDeliveryCost_expected,0)?></div>
                <div class="sb-val-tag">🚚 متوقعة</div>
            </div>
        </div>
    </div>
    <?php endif; ?>
    <div class="sb-row" style="background:var(--surf2);border-radius:var(--rsm);padding:12px 10px;margin-top:6px">
        <div class="sb-lbl" style="font-size:15px;font-weight:900;color:var(--ink)">💼 الربح الصافي (دج)</div>
        <div class="sb-vals">
            <div class="sb-val sv-confirmed">
                <div class="sb-val-num" style="font-size:20px;color:<?=$confirmed_net_profit>=0?'var(--green)':'var(--red)'?>"><?=($confirmed_net_profit>=0?'+':'').number_format($confirmed_net_profit,0)?></div>
                <div class="sb-val-tag">✅ مؤكد</div>
            </div>
            <div class="sb-val sv-expected">
                <div class="sb-val-num" style="font-size:20px;color:var(--exp)"><?=($expected_net_profit>=0?'+':'').number_format($expected_net_profit,0)?></div>
                <div class="sb-val-tag">🚚 متوقع</div>
            </div>
        </div>
    </div>
</div>

<!-- KPI — CONFIRMED -->
<div class="kpi-pair-wrap">
    <div class="kpi-pair-header">
        <span class="kpi-section-label ksl-confirmed">✅ الأرباح المؤكدة — طلبات تم استلامها</span>
        <div class="kpi-pair-divider"></div>
    </div>
    <div class="kpi-grid">
        <div class="kpi k-conf-blue confirmed-kpi">
            <span class="kpi-type-tag ktt-confirmed">مؤكد</span>
            <div class="kpi-top"><div class="kpi-icon" style="background:var(--bluel)">✅</div><span class="kpi-trend" style="background:var(--bluel);color:var(--blue)"><?=$totals['delivered_orders']??0?> طلب</span></div>
            <div class="kpi-val"><?=number_format($totals['delivered_orders']??0)?></div>
            <div class="kpi-lbl">طلبات مسلّمة</div>
            <div class="kpi-sub">إجمالي الطلبات: <?=$totals['total_orders']??0?></div>
        </div>
        <div class="kpi k-conf-teal confirmed-kpi">
            <span class="kpi-type-tag ktt-confirmed">مؤكد</span>
            <div class="kpi-top"><div class="kpi-icon" style="background:var(--teall)">💵</div></div>
            <div class="kpi-val pos"><?=number_format($totals['confirmed_revenue']??0,0)?></div>
            <div class="kpi-lbl">إيرادات مؤكدة (دج)</div>
            <div class="kpi-sub">تكلفة: <?=number_format($totals['confirmed_cost']??0,0)?> دج</div>
        </div>
        <div class="kpi k-conf-green confirmed-kpi">
            <span class="kpi-type-tag ktt-confirmed">مؤكد</span>
            <div class="kpi-top"><div class="kpi-icon" style="background:var(--greenl)">📈</div></div>
            <div class="kpi-val <?=$confirmed_gross_profit>=0?'pos':'neg'?>"><?=number_format($confirmed_gross_profit,0)?></div>
            <div class="kpi-lbl">ربح إجمالي مؤكد (دج)</div>
            <div class="kpi-sub">قبل خصم التوصيل</div>
        </div>
        <div class="kpi k-conf-purple confirmed-kpi">
            <span class="kpi-type-tag ktt-confirmed">مؤكد</span>
            <div class="kpi-top">
                <div class="kpi-icon" style="background:var(--greenl)">💼</div>
                <?php if($confirmed_net_profit>=0): ?>
                <span class="kpi-trend" style="background:var(--greenl);color:var(--green)">✓ ربح</span>
                <?php else: ?>
                <span class="kpi-trend" style="background:var(--redl);color:var(--red)">✗ خسارة</span>
                <?php endif; ?>
            </div>
            <div class="kpi-val <?=$confirmed_net_profit>=0?'pos':'neg'?>"><?=($confirmed_net_profit>=0?'+':'').number_format($confirmed_net_profit,0)?></div>
            <div class="kpi-lbl">ربح صافي مؤكد (دج)</div>
            <div class="kpi-sub">بعد توصيل + إرجاع + استبدال</div>
        </div>
        <div class="kpi k-conf-red confirmed-kpi">
            <span class="kpi-type-tag ktt-confirmed">مؤكد</span>
            <div class="kpi-top"><div class="kpi-icon" style="background:var(--redl)">⚠️</div></div>
            <div class="kpi-val neg"><?=number_format($confirmed_losses,0)?></div>
            <div class="kpi-lbl">خسائر مؤكدة (دج)</div>
            <div class="kpi-sub">توصيل: <?=number_format($totals['confirmed_delivery_paid']??0,0)?> | إرجاع: <?=number_format($totals['total_return_fees']??0,0)?></div>
        </div>
    </div>
</div>

<!-- KPI — EXPECTED -->
<div class="kpi-pair-wrap">
    <div class="kpi-pair-header">
        <span class="kpi-section-label ksl-expected">🚚 الأرباح المتوقعة — طلبات مرسلة في انتظار الاستلام</span>
        <div class="kpi-pair-divider"></div>
    </div>
    <div class="kpi-grid">
        <div class="kpi k-exp-blue expected-kpi">
            <span class="kpi-type-tag ktt-expected">متوقع</span>
            <div class="kpi-top"><div class="kpi-icon" style="background:var(--expl)">🚚</div><span class="kpi-trend" style="background:var(--expl);color:var(--exp)"><?=$totals['sent_orders']??0?> طلب</span></div>
            <div class="kpi-val exp"><?=number_format($totals['sent_orders']??0)?></div>
            <div class="kpi-lbl">طلبات مرسلة</div>
            <div class="kpi-sub">في طريقها للعميل</div>
        </div>
        <div class="kpi k-exp-teal expected-kpi">
            <span class="kpi-type-tag ktt-expected">متوقع</span>
            <div class="kpi-top"><div class="kpi-icon" style="background:var(--expl)">💜</div></div>
            <div class="kpi-val exp"><?=number_format($totals['expected_revenue']??0,0)?></div>
            <div class="kpi-lbl">إيرادات متوقعة (دج)</div>
            <div class="kpi-sub">تكلفة: <?=number_format($totals['expected_cost']??0,0)?> دج</div>
        </div>
        <div class="kpi k-exp-green expected-kpi">
            <span class="kpi-type-tag ktt-expected">متوقع</span>
            <div class="kpi-top"><div class="kpi-icon" style="background:var(--expl)">📊</div></div>
            <div class="kpi-val exp"><?=number_format($expected_gross_profit,0)?></div>
            <div class="kpi-lbl">ربح إجمالي متوقع (دج)</div>
            <div class="kpi-sub">قبل خصم التوصيل</div>
        </div>
        <div class="kpi k-exp-purple expected-kpi">
            <span class="kpi-type-tag ktt-expected">متوقع</span>
            <div class="kpi-top">
                <div class="kpi-icon" style="background:var(--expl)">🎯</div>
                <?php if($expected_net_profit>=0): ?>
                <span class="kpi-trend" style="background:var(--expl);color:var(--exp)">~ ربح</span>
                <?php else: ?>
                <span class="kpi-trend" style="background:var(--redl);color:var(--red)">~ خسارة</span>
                <?php endif; ?>
            </div>
            <div class="kpi-val exp"><?=($expected_net_profit>=0?'+':'').number_format($expected_net_profit,0)?></div>
            <div class="kpi-lbl">ربح صافي متوقع (دج)</div>
            <div class="kpi-sub">إذا تم استلام الكل</div>
        </div>
        <div class="kpi k-exp-red expected-kpi">
            <span class="kpi-type-tag ktt-expected">متوقع</span>
            <div class="kpi-top"><div class="kpi-icon" style="background:var(--expl)">🚛</div></div>
            <div class="kpi-val exp"><?=number_format($expected_losses,0)?></div>
            <div class="kpi-lbl">خسائر متوقعة (دج)</div>
            <div class="kpi-sub">توصيل: <?=number_format($totals['expected_delivery_paid']??0,0)?> | استبدال: <?=number_format($replacementDeliveryCost_expected,0)?></div>
        </div>
    </div>
</div>

<!-- RATE CARDS -->
<div class="rate-row">
    <div class="rate-card">
        <div class="rate-ring green"><?=$delivery_rate?>%</div>
        <div class="rate-info">
            <b>معدل التسليم</b>
            <small><?=$totals['delivered_orders']??0?> مسلّم من <?=$totals['total_orders']??0?> طلب</small>
            <div class="prog-wrap"><div class="prog-fill prog-green" style="width:<?=$delivery_rate?>%"></div></div>
        </div>
    </div>
    <div class="rate-card">
        <div class="rate-ring red"><?=$cancel_rate?>%</div>
        <div class="rate-info">
            <b>معدل الإلغاء</b>
            <small><?=$totals['cancelled_orders']??0?> طلب ملغي</small>
            <div class="prog-wrap"><div class="prog-fill prog-red" style="width:<?=$cancel_rate?>%"></div></div>
        </div>
    </div>
    <div class="rate-card">
        <div class="rate-ring green"><?=number_format($totals['confirmed_delivery_paid']??0,0)?></div>
        <div class="rate-info"><b>توصيل مؤكد (دج)</b><small>المسلّمة فعلياً ✅</small></div>
    </div>
    <div class="rate-card">
        <div class="rate-ring exp"><?=number_format($totals['expected_delivery_paid']??0,0)?></div>
        <div class="rate-info"><b>توصيل متوقع (دج)</b><small>المرسلة 🚚</small></div>
    </div>
    <div class="rate-card">
        <div class="rate-ring amber"><?=number_format($totals['total_return_fees']??0,0)?></div>
        <div class="rate-info"><b>رسوم الإرجاع (دج)</b><small>من الطلبات الملغاة ❌</small></div>
    </div>
    <?php if($replacementDeliveryCost>0||$totalReplacementsCount>0): ?>
    <div class="rate-card">
        <div class="rate-ring rose"><?=number_format($replacementDeliveryCost,0)?></div>
        <div class="rate-info"><b>توصيل الاستبدالات (دج)</b><small><?=$totalReplacementsCount?> استبدال — على البائع</small></div>
    </div>
    <?php endif; ?>
</div>

<!-- CHARTS -->
<div class="charts-grid">
    <div class="chart-card">
        <div class="section-title"><div class="sti">📊</div>أكثر المنتجات ربحاً (مؤكد vs متوقع)</div>
        <div class="chart-container">
            <?php if(empty($topProducts)): ?><div class="chart-empty"><span class="ce">📭</span>لا توجد بيانات في هذه الفترة</div>
            <?php else: ?><canvas id="c1"></canvas><?php endif; ?>
        </div>
    </div>
    <div class="chart-card">
        <div class="section-title"><div class="sti">🥧</div>توزيع الأرباح المؤكدة حسب الفئة</div>
        <div class="chart-container">
            <?php if(empty($categories)): ?><div class="chart-empty"><span class="ce">📭</span>لا توجد بيانات في هذه الفترة</div>
            <?php else: ?><canvas id="c2"></canvas><?php endif; ?>
        </div>
    </div>
    <div class="chart-card">
        <div class="section-title"><div class="sti" style="background:var(--redl)">🚫</div>أكثر المنتجات إلغاءً</div>
        <div class="chart-container">
            <?php if(empty($mostCancelled)): ?><div class="chart-empty"><span class="ce">✅</span>لا توجد إلغاءات في هذه الفترة</div>
            <?php else: ?><canvas id="c3"></canvas><?php endif; ?>
        </div>
    </div>
    <div class="chart-card">
        <div class="section-title"><div class="sti" style="background:var(--amberl)">🚚</div>إحصاءات شركات التوصيل</div>
        <div class="chart-container">
            <?php if(empty($deliveryStats)): ?><div class="chart-empty"><span class="ce">📭</span>لا توجد بيانات في هذه الفترة</div>
            <?php else: ?><canvas id="c4"></canvas><?php endif; ?>
        </div>
    </div>
</div>

<!-- TOP PRODUCTS -->
<?php if(!empty($topProducts)): ?>
<div class="section-title" style="animation:fadeUp .4s ease both"><div class="sti">🏆</div>أكثر 10 منتجات ربحاً — مؤكد ومتوقع</div>
<div class="prod-grid">
<?php
$maxConfirmed = max(array_map(fn($p)=>floatval($p['confirmed_profit']??0), $topProducts) ?: [1]);
$maxExpected  = max(array_map(fn($p)=>floatval($p['expected_profit']??0), $topProducts) ?: [1]);
foreach($topProducts as $idx=>$p):
    $cp = floatval($p['confirmed_profit'] ?? 0);
    $ep = floatval($p['expected_profit']  ?? 0);
    $totalRevenue = floatval($p['confirmed_revenue']??0) + floatval($p['expected_revenue']??0);
    $totalProfit  = $cp + $ep;
    $margin = $totalRevenue > 0 ? ($totalProfit / $totalRevenue * 100) : 0;
    $confirmedMargin = floatval($p['confirmed_revenue']??0) > 0 ? ($cp / floatval($p['confirmed_revenue']??1) * 100) : 0;
    $rankCls = $idx==0?'gold':($idx==1?'silver':($idx==2?'bronze':'normal'));
    $rankLbl = $idx==0?'🥇':($idx==1?'🥈':($idx==2?'🥉':'#'.($idx+1)));
    // عرض الشريطين: مؤكد + متوقع
    $totalWidth = $totalRevenue > 0 ? min(100, $totalProfit / max($maxConfirmed,$maxExpected,1) * 100) : 0;
    $confirmedW = ($cp + $ep) > 0 ? min(100, $cp / ($cp + $ep) * 100) : 0;
?>
<div class="prod-card">
    <div class="pc-header">
        <div class="pc-rank <?=$rankCls?>"><?=$rankLbl?></div>
        <div>
            <div class="pc-name" title="<?=htmlspecialchars($p['product_name'])?>"><?=htmlspecialchars($p['product_name'])?></div>
            <div class="pc-cat"><?=htmlspecialchars($p['category_name']??'غير مصنف')?> • 🚚 <?=$p['sent_count']??0?> مرسل</div>
        </div>
    </div>
    <div class="pc-body">
        <div class="pc-stat confirmed-stat">
            <div class="pc-stat-lbl">✅ ربح مؤكد</div>
            <div class="pc-stat-val pos"><?=number_format($cp,0)?></div>
        </div>
        <div class="pc-stat expected-stat">
            <div class="pc-stat-lbl">🚚 ربح متوقع</div>
            <div class="pc-stat-val exp"><?=number_format($ep,0)?></div>
        </div>
        <div class="pc-stat">
            <div class="pc-stat-lbl">الكمية</div>
            <div class="pc-stat-val"><?=number_format($p['total_quantity_sold']??0)?></div>
        </div>
        <div class="pc-stat">
            <div class="pc-stat-lbl">الملغيات</div>
            <div class="pc-stat-val <?=($p['cancelled_count']??0)>0?'neg':''?>"><?=$p['cancelled_count']??0?></div>
        </div>
    </div>
    <div class="pc-bar-wrap">
        <div class="pc-bar-lbl">
            <span>مؤكد <span style="color:var(--green)"><?=number_format($confirmedMargin,0)?>%</span> | متوقع <span style="color:var(--exp)"><?=number_format(100-$confirmedMargin,0)?>%</span></span>
        </div>
        <div class="pc-bar" style="overflow:visible">
            <div class="pc-bar-fill fg" style="width:<?=number_format($confirmedW,1)?>%"></div>
            <div class="pc-bar-fill fexp" style="width:<?=number_format(100-$confirmedW,1)?>%;border-radius:0 10px 10px 0"></div>
        </div>
    </div>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>

<!-- MOST CANCELLED -->
<?php if(!empty($mostCancelled)): ?>
<div class="section-title" style="animation:fadeUp .4s ease both"><div class="sti" style="background:var(--redl)">⚠️</div>أكثر المنتجات إلغاءً</div>
<div class="prod-grid">
<?php foreach($mostCancelled as $idx=>$p):
    $rate=$p['cancellation_rate']??0;
    $rbc=$rate>30?'fr':($rate>15?'fa':'fg');
?>
<div class="prod-card">
    <div class="pc-header">
        <div class="pc-rank normal" style="background:var(--redl);color:var(--red);border:1px solid var(--redsat)"><?=$idx+1?></div>
        <div>
            <div class="pc-name" title="<?=htmlspecialchars($p['product_name'])?>"><?=htmlspecialchars($p['product_name'])?></div>
            <div class="pc-cat"><?=htmlspecialchars($p['category_name']??'غير مصنف')?></div>
        </div>
    </div>
    <div class="pc-body">
        <div class="pc-stat"><div class="pc-stat-lbl">الملغيات</div><div class="pc-stat-val neg"><?=number_format($p['cancelled_orders']??0)?></div></div>
        <div class="pc-stat"><div class="pc-stat-lbl">المسلّمة ✅</div><div class="pc-stat-val pos"><?=number_format($p['delivered_orders']??0)?></div></div>
        <div class="pc-stat expected-stat"><div class="pc-stat-lbl">المرسلة 🚚</div><div class="pc-stat-val exp"><?=number_format($p['sent_orders']??0)?></div></div>
        <div class="pc-stat" style="grid-column:span 1"><div class="pc-stat-lbl">خسارة التكلفة</div><div class="pc-stat-val neg"><?=number_format($p['cancelled_cost']??0,0)?></div></div>
    </div>
    <div class="pc-bar-wrap">
        <div class="pc-bar-lbl"><span>نسبة الإلغاء</span><span><?=$rate?>%</span></div>
        <div class="pc-bar"><div class="pc-bar-fill <?=$rbc?>" style="width:<?=min($rate,100)?>%"></div></div>
    </div>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>

<!-- DELIVERY COMPANIES -->
<?php if(!empty($deliveryStats)): ?>
<div class="section-title" style="animation:fadeUp .4s ease both"><div class="sti" style="background:var(--amberl)">🚚</div>شركات التوصيل</div>
<div class="dc-grid">
<?php foreach($deliveryStats as $dc): ?>
<div class="dc-card">
    <div class="dc-name">🚛 <?=htmlspecialchars($dc['company_name']??'غير معروف')?></div>
    <div class="dc-stats">
        <div class="dc-row"><span class="dc-row-lbl">مسلّمة ✅</span><span class="dc-row-val" style="color:var(--green)"><?=number_format($dc['delivered_orders']??0)?></span></div>
        <div class="dc-row"><span class="dc-row-lbl">مرسلة 🚚</span><span class="dc-row-val" style="color:var(--exp)"><?=number_format($dc['sent_orders']??0)?></span></div>
        <div class="dc-row"><span class="dc-row-lbl">ملغاة ❌</span><span class="dc-row-val" style="color:var(--red)"><?=number_format($dc['cancelled_orders']??0)?></span></div>
        <div class="dc-row"><span class="dc-row-lbl">رسوم إرجاع/طلب</span><span class="dc-row-val"><?=number_format($dc['return_fee']??200,0)?> دج</span></div>
        <div class="dc-div"></div>
        <div class="dc-row"><span class="dc-row-lbl">إجمالي خسارة الإرجاع</span><span class="dc-row-val" style="color:var(--red)"><?=number_format($dc['total_return_fees']??0,0)?> دج</span></div>
    </div>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>

<!-- CATEGORIES TABLE -->
<?php if(!empty($categories)): ?>
<div class="table-wrap">
    <div class="section-title"><div class="sti">📁</div>أداء الفئات</div>
    <div class="table-scroll">
    <table class="dt">
        <thead><tr><th>الفئة</th><th>الطلبات</th><th>الكمية</th><th>الإيرادات</th><th>ربح مؤكد ✅</th><th>ربح متوقع 🚚</th><th>نسبة الإلغاء</th></tr></thead>
        <tbody>
        <?php foreach($categories as $cat):
            $cr=($cat['orders_count']??0)>0?(($cat['cancelled_count']??0)/($cat['orders_count']??1)*100):0;
            $cp=floatval($cat['confirmed_profit']??0);
            $ep=floatval($cat['expected_profit']??0);
        ?>
        <tr>
            <td style="font-weight:800;color:var(--ink)"><?=htmlspecialchars($cat['category_name']??'غير مصنف')?></td>
            <td class="mono"><?=number_format($cat['orders_count']??0)?></td>
            <td class="mono"><?=number_format($cat['total_quantity_sold']??0)?></td>
            <td class="mono"><?=number_format($cat['total_revenue']??0,0)?> دج</td>
            <td class="<?=$cp>=0?'profit-pos':'profit-neg'?>"><?=number_format($cp,0)?> دج</td>
            <td class="profit-exp"><?=number_format($ep,0)?> دج</td>
            <td><span class="badge <?=$cr>20?'b-danger':($cr>10?'b-warning':'b-success')?>"><?=number_format($cr,1)?>%</span></td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    </div>
</div>
<?php endif; ?>

<!-- ORDERS TABLE -->
<div class="table-wrap">
    <div class="section-title">
        <div class="sti">🕐</div>
        آخر 50 طلب في الفترة المحددة
        <span style="font-size:11px;color:var(--mut);font-weight:600;margin-right:auto"><?=count($lastOrders)?> طلب</span>
    </div>
    <?php if($totalReplacementsCount>0): ?>
    <div class="info-alert">🔄 <strong><?=$totalReplacementsCount?> استبدال</strong> — تكلفة توصيلها <strong style="font-family:'IBM Plex Mono',monospace"><?=number_format($replacementDeliveryCost,0)?> دج</strong> مخصومة من الأرباح</div>
    <?php endif; ?>
    <div class="table-scroll">
    <table class="dt">
        <thead>
            <tr>
                <th>#</th><th>العميل</th><th>التاريخ</th><th>الحالة</th>
                <th>المبيع</th><th>التوصيل</th><th>استبدال</th>
                <th>الربح / الخسارة</th><th>النوع</th>
            </tr>
        </thead>
        <tbody>
        <?php if(empty($lastOrders)): ?>
            <tr><td colspan="9" style="text-align:center;padding:40px;color:var(--mut)">📭 لا توجد طلبات في هذه الفترة</td></tr>
        <?php else: ?>
        <?php foreach($lastOrders as $order):
            $oid=$order['id'];
            $t=$orderTotals[$oid]??['selling'=>0,'purchase'=>0,'delivery'=>0,'repl_delivery'=>0,'repl_count'=>0,'profit'=>0,'profit_type'=>'loss'];
            if($order['status_id']==3){$bc='b-success';$bt='✅ مسلّم';}
            elseif($order['status_id']==2){$bc='b-expected';$bt='🚚 مرسل';}
            elseif($order['status_id']==4){$bc='b-danger';$bt='❌ ملغي';}
            else{$bc='b-warning';$bt='⏳ انتظار';}
            $hasRepl=($t['repl_count']??0)>0;
            $rowClass = $hasRepl ? 'repl-hl ' : '';
            $rowClass .= ($t['profit_type']==='confirmed') ? 'row-confirmed' : (($t['profit_type']==='expected') ? 'row-expected' : '');

            // لون الربح حسب النوع
            $profitClass = 'profit-neg';
            $profitPrefix = '';
            if($t['profit_type']==='confirmed' && $t['profit']>=0){ $profitClass='profit-pos'; $profitPrefix='+'; }
            elseif($t['profit_type']==='expected' && $t['profit']>=0){ $profitClass='profit-exp'; $profitPrefix='~'; }
            elseif($t['profit']<0){ $profitClass='profit-neg'; }
        ?>
        <tr class="<?=$rowClass?>">
            <td>#<?=$oid?></td>
            <td><?=htmlspecialchars($order['customer_name'])?>
                <?php if($hasRepl): ?><br><span class="repl-badge">🔄 <?=$t['repl_count']?> استبدال</span><?php endif; ?>
            </td>
            <td style="font-size:12px;color:var(--mut);white-space:nowrap"><?=date('Y-m-d',strtotime($order['order_date']))?></td>
            <td><span class="badge <?=$bc?>"><?=$bt?></span></td>
            <td class="mono"><?=number_format($t['selling'],0)?> دج</td>
            <td class="mono"><?=$t['delivery']>0?number_format($t['delivery'],0).' دج':'—'?></td>
            <td><?php if($t['repl_delivery']>0): ?><span class="mono" style="color:var(--purple)">-<?=number_format($t['repl_delivery'],0)?> دج</span><?php else: ?><span style="color:var(--mut2)">—</span><?php endif; ?></td>
            <td class="<?=$profitClass?>"><?=$profitPrefix.number_format($t['profit'],0)?> دج</td>
            <td>
                <?php if($t['profit_type']==='confirmed'): ?>
                <span class="badge b-success" style="font-size:10px">✅ مؤكد</span>
                <?php elseif($t['profit_type']==='expected'): ?>
                <span class="badge b-expected" style="font-size:10px">🚚 متوقع</span>
                <?php else: ?>
                <span class="badge b-danger" style="font-size:10px">❌ خسارة</span>
                <?php endif; ?>
            </td>
        </tr>
        <?php endforeach; ?>
        <?php endif; ?>
        </tbody>
    </table>
    </div>
</div>

</div><!-- /container -->

<script>
// ══ CHARTS ══
<?php if(!empty($topProducts)): ?>
(function(){
    const labels=<?=json_encode(array_map(fn($p)=>mb_strimwidth($p['product_name'],0,18,'…'),array_slice($topProducts,0,7)))?>;
    const confirmed=<?=json_encode(array_map(fn($p)=>floatval($p['confirmed_profit']??0),array_slice($topProducts,0,7)))?>;
    const expected=<?=json_encode(array_map(fn($p)=>floatval($p['expected_profit']??0),array_slice($topProducts,0,7)))?>;
    const ctx=document.getElementById('c1');if(!ctx)return;
    new Chart(ctx,{type:'bar',data:{labels,datasets:[
        {label:'مؤكد ✅',data:confirmed,backgroundColor:'rgba(16,185,129,0.85)',borderRadius:8,borderSkipped:false},
        {label:'متوقع 🚚',data:expected,backgroundColor:'rgba(139,92,246,0.75)',borderRadius:8,borderSkipped:false}
    ]},options:{responsive:true,maintainAspectRatio:false,
    plugins:{legend:{display:true,position:'top',labels:{font:{family:'Tajawal',size:12},padding:10,usePointStyle:true}},tooltip:{rtl:true,bodyFont:{family:'Tajawal'},titleFont:{family:'Tajawal'}}},
    scales:{y:{beginAtZero:true,stacked:false,ticks:{font:{family:'Tajawal',size:11},callback:v=>v.toLocaleString()}},x:{ticks:{font:{family:'Tajawal',size:10},maxRotation:30},grid:{display:false}}}}});
})();
<?php endif; ?>

<?php if(!empty($categories)): ?>
(function(){
    const raw=<?=json_encode(array_slice($categories,0,6))?>;
    const labels=raw.map(c=>c.category_name||'غير مصنف');
    const data=raw.map(c=>Math.max(0,parseFloat(c.confirmed_profit||0)));
    const ctx=document.getElementById('c2');if(!ctx)return;
    new Chart(ctx,{type:'doughnut',data:{labels,datasets:[{data,backgroundColor:['#10B981','#047857','#34D399','#6EE7B7','#A7F3D0','#D1FAE5'],borderWidth:4,borderColor:document.documentElement.getAttribute('data-theme')==='dark'?'#161D30':'#fff',hoverOffset:10}]},
    options:{responsive:true,maintainAspectRatio:false,cutout:'60%',plugins:{legend:{display:true,position:'bottom',labels:{font:{family:'Tajawal',size:11},padding:12,usePointStyle:true}},tooltip:{rtl:true,bodyFont:{family:'Tajawal'},titleFont:{family:'Tajawal'}}}}});
})();
<?php endif; ?>

<?php if(!empty($mostCancelled)): ?>
(function(){
    const labels=<?=json_encode(array_map(fn($p)=>mb_strimwidth($p['product_name'],0,18,'…'),array_slice($mostCancelled,0,6)))?>;
    const data=<?=json_encode(array_map(fn($p)=>intval($p['cancelled_orders']),array_slice($mostCancelled,0,6)))?>;
    const ctx=document.getElementById('c3');if(!ctx)return;
    new Chart(ctx,{type:'bar',data:{labels,datasets:[{label:'ملغيات',data,backgroundColor:'rgba(239,68,68,0.82)',borderRadius:10,borderSkipped:false}]},
    options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{display:false},tooltip:{rtl:true,bodyFont:{family:'Tajawal'},titleFont:{family:'Tajawal'}}},
    scales:{y:{beginAtZero:true,ticks:{font:{family:'Tajawal',size:11}}},x:{ticks:{font:{family:'Tajawal',size:10},maxRotation:30},grid:{display:false}}}}});
})();
<?php endif; ?>

<?php if(!empty($deliveryStats)): ?>
(function(){
    const labels=<?=json_encode(array_column($deliveryStats,'company_name'))?>;
    const delivered=<?=json_encode(array_map(fn($d)=>intval($d['delivered_orders']),$deliveryStats))?>;
    const sent=<?=json_encode(array_map(fn($d)=>intval($d['sent_orders']),$deliveryStats))?>;
    const cancelled=<?=json_encode(array_map(fn($d)=>intval($d['cancelled_orders']),$deliveryStats))?>;
    const ctx=document.getElementById('c4');if(!ctx)return;
    new Chart(ctx,{type:'bar',data:{labels,datasets:[
        {label:'مسلّم ✅',data:delivered,backgroundColor:'rgba(16,185,129,0.82)',borderRadius:6,borderSkipped:false},
        {label:'مرسل 🚚',data:sent,backgroundColor:'rgba(139,92,246,0.75)',borderRadius:6,borderSkipped:false},
        {label:'ملغي ❌',data:cancelled,backgroundColor:'rgba(239,68,68,0.75)',borderRadius:6,borderSkipped:false}
    ]},options:{responsive:true,maintainAspectRatio:false,
    plugins:{legend:{display:true,position:'top',labels:{font:{family:'Tajawal',size:12},padding:12,usePointStyle:true}},tooltip:{rtl:true,bodyFont:{family:'Tajawal'},titleFont:{family:'Tajawal'}}},
    scales:{y:{beginAtZero:true,ticks:{font:{family:'Tajawal',size:11}}},x:{ticks:{font:{family:'Tajawal'}},grid:{display:false}}}}});
})();
<?php endif; ?>

// ══ DARK MODE ══
function toggleDark(){
    const html=document.documentElement;
    const dark=html.getAttribute('data-theme')==='dark';
    html.setAttribute('data-theme',dark?'light':'dark');
    document.getElementById('dmToggle').textContent=dark?'🌙':'☀️';
    localStorage.setItem('profitsDM',dark?'light':'dark');
}
(function(){
    const s=localStorage.getItem('profitsDM')||'light';
    document.documentElement.setAttribute('data-theme',s);
    const b=document.getElementById('dmToggle');
    if(b)b.textContent=s==='dark'?'☀️':'🌙';
})();
</script>
</body>
</html>