<?php
// modules/subscriptions/subscriptions.php
if (session_status() === PHP_SESSION_NONE) { session_start(); }

require_once '../../includes/auth.php';
checkLogin();

$isAdmin = isAdmin();
$userId = $_SESSION['user_id'];

require_once '../../config/db.php';

// دروازه امنیتی (Live Sync Proxy)
if (isset($_GET['sub_ajax'])) {
    require_once '../pasarguard/pasarguard_api.php';
    exit;
}

$msg = $_GET['msg'] ?? '';
$error = $_GET['error'] ?? '';

// پردازش فیلترهای دیتابیس
$where = ["i.status = 'sold'"];
$params = [];

if (!$isAdmin) {
    $where[] = "i.operator_id = ?";
    $params[] = $userId;
}

$dateFilter = $_GET['date_filter'] ?? '';
if ($dateFilter === 'today') {
    $where[] = "DATE(i.sold_at) = CURDATE()";
} elseif ($dateFilter === 'yesterday') {
    $where[] = "DATE(i.sold_at) = SUBDATE(CURDATE(), 1)";
} elseif ($dateFilter === 'custom' && !empty($_GET['start_date']) && !empty($_GET['end_date'])) {
    $where[] = "DATE(i.sold_at) BETWEEN ? AND ?";
    $params[] = $_GET['start_date'];
    $params[] = $_GET['end_date'];
}

$whereClause = implode(" AND ", $where);

// 💡 اصلاح کوئری برای استخراج نام مشتری، شناسه تراکنش و بانک حساب واریزی
$sqlList = "SELECT i.*, p.color_code, 
            u.fullname AS seller_name,
            t_latest.id AS tx_id, t_latest.customer_name, t_latest.bank_id,
            tx.total_paid, tx.total_admin_profit, tx.total_profit
            FROM inventory i 
            LEFT JOIN plans p ON i.plan_name = p.plan_name
            LEFT JOIN users u ON i.operator_id = u.id
            LEFT JOIN (
                SELECT account_username, MAX(id) as latest_tx_id,
                       SUM(paid_amount) AS total_paid, 
                       SUM(admin_profit) AS total_admin_profit, 
                       SUM(profit) AS total_profit 
                FROM transactions 
                GROUP BY account_username
            ) tx ON i.account_username = tx.account_username
            LEFT JOIN transactions t_latest ON tx.latest_tx_id = t_latest.id
            WHERE $whereClause 
            ORDER BY i.sold_at DESC";

$stmt = $pdo->prepare($sqlList);
$stmt->execute($params);
$subscriptions = $stmt->fetchAll(PDO::FETCH_ASSOC);

$usedServerIds = array_unique(array_filter(array_column($subscriptions, 'server_id')));
if (empty($usedServerIds)) $usedServerIds = [1];

// استخراج لیست بانک‌ها برای منوی واریز در مودال ویرایش تراز
$banksList = [];
try {
    if ($isAdmin) {
        $banksList = $pdo->query("SELECT * FROM banks ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
    } else {
        // نمایندگان فقط بانک‌های خودشان و بانک‌های مدیر کل (user_id = 1) را ببینند
        $banksList = $pdo->query("SELECT * FROM banks WHERE user_id = $userId OR user_id = 1 ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
    }
} catch(Exception $e) {}

// پردازش فرم ویرایش تراز مالی (در صورتی که سابمیت شود)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'edit_sub') {
    try {
        $tx_id = $_POST['tx_id'] ?? null;
        $customer_name = $_POST['customer_name'] ?? '';
        $paid_amount = str_replace(',', '', $_POST['paid_amount'] ?? '0');
        $bank_id = !empty($_POST['bank_id']) ? $_POST['bank_id'] : null;

        if ($tx_id) {
            $stmt = $pdo->prepare("UPDATE transactions SET customer_name = ?, paid_amount = ?, bank_id = ? WHERE id = ?");
            $stmt->execute([$customer_name, $paid_amount, $bank_id, $tx_id]);
            header("Location: subscriptions.php?msg=success");
            exit;
        }
    } catch(Exception $e) {}
}

require_once '../../includes/header.php';
?>

<style>
    main .max-w-7xl { max-width: 100% !important; margin: 0 !important; padding: 0 1rem !important; }
    .custom-scrollbar::-webkit-scrollbar { width: 4px; height: 4px; }
    .custom-scrollbar::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 10px; }
    html.dark .custom-scrollbar::-webkit-scrollbar-thumb { background: #475569; }
</style>

<div class="w-full pb-10">
    <?php if($msg === 'success'): ?>
        <div class="bg-emerald-50 border border-emerald-200 text-emerald-800 px-5 py-4 rounded-2xl mb-6 font-bold shadow-sm flex items-center gap-2">
            <span>✅</span> عملیات با موفقیت انجام شد.
        </div>
    <?php endif; ?>

    <?php include 'widgets/stats_and_filters.php'; ?>
    <?php include 'widgets/subs_table.php'; ?>
</div>

<?php include 'widgets/scripts.php'; ?>
<?php require_once '../../includes/footer.php'; ?>