<?php
// modules/billing.php
require_once '../includes/auth.php';
checkLogin();
require_once '../config/db.php';

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

// ==========================================
// پردازش عملیات‌های فرم (ثبت تسویه، تایید، رد)
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    
    if ($_POST['action'] == 'request_settlement' && !$isAdmin) {
        if (empty($_POST['tx_ids'])) {
            $error = "حداقل یک تراکنش را برای تسویه انتخاب کنید.";
        } else {
            $txIds = $_POST['tx_ids']; 
            $receiptText = trim($_POST['receipt_text']);
            $receiptFile = null;

            if (isset($_FILES['receipt_file']) && $_FILES['receipt_file']['error'] === UPLOAD_ERR_OK) {
                $ext = pathinfo($_FILES['receipt_file']['name'], PATHINFO_EXTENSION);
                $allowed = ['jpg', 'jpeg', 'png', 'pdf'];
                if (in_array(strtolower($ext), $allowed)) {
                    $receiptFile = time() . '_' . rand(100, 999) . '.' . $ext;
                    if (!is_dir('../uploads/receipts/')) { mkdir('../uploads/receipts/', 0777, true); }
                    move_uploaded_file($_FILES['receipt_file']['tmp_name'], '../uploads/receipts/' . $receiptFile);
                } else {
                    $error = "فرمت فایل مجاز نیست (فقط عکس یا PDF).";
                }
            }

            if (!$error) {
                $placeholders = implode(',', array_fill(0, count($txIds), '?'));
                $calcSql = "SELECT SUM(paid_amount - profit) as total_amount FROM transactions WHERE id IN ($placeholders) AND user_id = ?";
                $params = array_merge($txIds, [$userId]);
                $stmtCalc = $pdo->prepare($calcSql);
                $stmtCalc->execute($params);
                $totalAmount = $stmtCalc->fetch()['total_amount'];

                if ($totalAmount > 0) {
                    $stmtSettlement = $pdo->prepare("INSERT INTO settlements (user_id, amount, receipt_text, receipt_file, status) VALUES (?, ?, ?, ?, 'pending')");
                    $stmtSettlement->execute([$userId, $totalAmount, $receiptText, $receiptFile]);
                    $settlementId = $pdo->lastInsertId();

                    $updateSql = "UPDATE transactions SET settlement_id = ? WHERE id IN ($placeholders) AND user_id = ?";
                    $updateParams = array_merge([$settlementId], $txIds, [$userId]);
                    $stmtUpdate = $pdo->prepare($updateSql);
                    $stmtUpdate->execute($updateParams);

                    $msg = "درخواست تسویه شما با موفقیت ثبت شد و منتظر تایید مدیریت است.";
                }
            }
        }
    }

    if (in_array($_POST['action'], ['approve_settlement', 'reject_settlement']) && $isAdmin) {
        $sId = (int)$_POST['settlement_id'];
        $newStatus = ($_POST['action'] == 'approve_settlement') ? 'approved' : 'rejected';
        
        $stmtStatus = $pdo->prepare("UPDATE settlements SET status = ? WHERE id = ?");
        $stmtStatus->execute([$newStatus, $sId]);

        if ($newStatus == 'approved') {
            $pdo->prepare("UPDATE transactions SET is_settled = 1 WHERE settlement_id = ?")->execute([$sId]);
            $msg = "تسویه با موفقیت تایید شد.";
        } else {
            $pdo->prepare("UPDATE transactions SET settlement_id = NULL WHERE settlement_id = ?")->execute([$sId]);
            $msg = "تسویه رد شد و تراکنش‌ها به لیست بدهی اپراتور برگشتند.";
        }
    }
}

// ==========================================
// منطق بخش گزارش‌گیری جامع مالی
// ==========================================
$operatorsList = $isAdmin ? $pdo->query("SELECT id, username FROM users WHERE role = 'operator' ORDER BY id ASC")->fetchAll() : [];

$report_user = $_GET['report_user'] ?? '';
$report_status = $_GET['report_status'] ?? 'all';

$r_conditions = [];
$r_params = [];

if (!$isAdmin) {
    $r_conditions[] = "t.user_id = :uid";
    $r_params[':uid'] = $userId;
} elseif ($isAdmin && !empty($report_user)) {
    $r_conditions[] = "t.user_id = :uid";
    $r_params[':uid'] = $report_user;
}

if ($report_status === 'settled') {
    $r_conditions[] = "t.is_settled = 1";
} elseif ($report_status === 'unsettled') {
    $r_conditions[] = "t.is_settled = 0";
}

$r_whereSQL = (!empty($r_conditions)) ? "WHERE " . implode(" AND ", $r_conditions) : "";

$sqlReport = "SELECT t.*, u.username as creator, s.status as settle_status 
              FROM transactions t 
              LEFT JOIN users u ON t.user_id = u.id 
              LEFT JOIN settlements s ON t.settlement_id = s.id
              $r_whereSQL ORDER BY t.id DESC";
$stmtReport = $pdo->prepare($sqlReport);
$stmtReport->execute($r_params);
$reportData = $stmtReport->fetchAll();

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

<link rel="stylesheet" type="text/css" href="/vpnet-panel/assets/css/datatables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.dataTables.min.css">
<style>
    .dt-buttons .dt-button {
        background-color: #f3f4f6 !important; border: 1px solid #d1d5db !important; border-radius: 8px !important;
        color: #374151 !important; font-family: 'Vazirmatn', sans-serif !important; font-weight: bold !important;
        padding: 6px 12px !important; margin-left: 8px !important; transition: all 0.2s !important;
    }
    .dt-buttons .dt-button.buttons-excel { background-color: #ecfdf5 !important; border-color: #10b981 !important; color: #047857 !important; }
    .dt-buttons .dt-button.buttons-print { background-color: #eff6ff !important; border-color: #3b82f6 !important; color: #1d4ed8 !important; }
</style>

<?php if($msg): ?><div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded-xl mb-6 font-bold shadow-sm">✅ <?php echo $msg; ?></div><?php endif; ?>
<?php if($error): ?><div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-xl mb-6 font-bold shadow-sm">❌ <?php echo $error; ?></div><?php endif; ?>

<?php if(!$isAdmin): ?>
    <?php
    $stmtUnpaid = $pdo->prepare("SELECT *, (paid_amount - profit) as debt_amount FROM transactions WHERE user_id = ? AND is_settled = 0 AND settlement_id IS NULL ORDER BY id DESC");
    $stmtUnpaid->execute([$userId]);
    $unpaidTx = $stmtUnpaid->fetchAll();
    
    $stmtHistory = $pdo->prepare("SELECT * FROM settlements WHERE user_id = ? ORDER BY id DESC LIMIT 10");
    $stmtHistory->execute([$userId]);
    $history = $stmtHistory->fetchAll();
    ?>
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-12">
        <div class="lg:col-span-2 bg-white rounded-3xl shadow-sm border border-gray-100 p-8 border-t-8 border-t-blue-600">
            <h2 class="text-xl font-bold mb-6 text-gray-800">تراکنش‌های باز (بدهی شما)</h2>
            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="action" value="request_settlement">
                <div class="overflow-x-auto mb-6">
                    <table class="w-full text-sm text-right text-gray-500">
                        <thead class="bg-gray-100 text-gray-700">
                            <tr>
                                <th class="px-3 py-3"><input type="checkbox" id="selectAll" class="w-4 h-4 cursor-pointer"></th>
                                <th class="px-3 py-3">تاریخ</th>
                                <th class="px-3 py-3">نام مشتری</th>
                                <th class="px-3 py-3">نام کاربری (اکانت)</th>
                                <th class="px-3 py-3">نوع</th>
                                <th class="px-3 py-3 text-red-600 font-bold">بدهی (تومان)</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $totalCurrentDebt = 0; if(empty($unpaidTx)): ?>
                                <tr><td colspan="6" class="text-center py-6 text-gray-400">بدهی ثبت نشده‌ای ندارید.</td></tr>
                            <?php else: foreach($unpaidTx as $tx): $totalCurrentDebt += $tx['debt_amount']; ?>
                                <tr class="border-b hover:bg-gray-50 cursor-pointer">
                                    <td class="px-3 py-3"><input type="checkbox" name="tx_ids[]" value="<?php echo $tx['id']; ?>" class="w-4 h-4 tx-checkbox"></td>
                                    <td class="px-3 py-3" dir="ltr"><?php echo $tx['date_shamsi']; ?></td>
                                    <td class="px-3 py-3 font-bold text-gray-800"><?php echo htmlspecialchars($tx['customer_name']); ?></td>
                                    <td class="px-3 py-3 font-mono text-blue-600" dir="ltr"><?php echo htmlspecialchars($tx['account_username']); ?></td>
                                    <td class="px-3 py-3"><?php echo $tx['type'] == 'new' ? '<span class="text-green-600 font-bold">جدید</span>' : '<span class="text-blue-600 font-bold">تمدید</span>'; ?></td>
                                    <td class="px-3 py-3 font-bold text-red-600"><?php echo number_format($tx['debt_amount']); ?></td>
                                </tr>
                            <?php endforeach; endif; ?>
                        </tbody>
                        <?php if(!empty($unpaidTx)): ?>
                        <tfoot class="bg-red-50">
                            <tr>
                                <td colspan="5" class="px-3 py-3 font-bold text-gray-800">مجموع کل بدهی فعلی:</td>
                                <td class="px-3 py-3 font-black text-red-700 text-lg"><?php echo number_format($totalCurrentDebt); ?></td>
                            </tr>
                        </tfoot>
                        <?php endif; ?>
                    </table>
                </div>

                <div class="bg-gray-50 p-4 rounded-xl border border-gray-200">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div><label class="block text-xs font-bold mb-1">یادداشت</label><input type="text" name="receipt_text" class="w-full border p-2 rounded-lg"></div>
                        <div><label class="block text-xs font-bold mb-1">فیش واریزی</label><input type="file" name="receipt_file" class="w-full border p-1.5 rounded-lg bg-white" accept="image/*,.pdf"></div>
                    </div>
                    <button type="submit" class="mt-4 bg-blue-600 text-white px-6 py-2 rounded-lg font-bold hover:bg-blue-700">ارسال درخواست تسویه</button>
                </div>
            </form>
        </div>

        <div class="bg-white rounded-3xl shadow-sm border border-gray-100 p-8 h-fit">
            <h2 class="text-xl font-bold mb-4 text-gray-800">وضعیت تسویه‌های اخیر</h2>
            <div class="space-y-3">
                <?php foreach($history as $h): ?>
                    <div class="border p-3 rounded-lg text-sm <?php echo $h['status']=='approved' ? 'bg-green-50 border-green-200' : ($h['status']=='rejected' ? 'bg-red-50 border-red-200' : 'bg-yellow-50 border-yellow-200'); ?>">
                        <div class="flex justify-between font-bold mb-1">
                            <span><?php echo number_format($h['amount']); ?> تومان</span>
                            <span><?php echo $h['status']=='approved' ? '✅' : ($h['status']=='rejected' ? '❌' : '⏳'); ?></span>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
<?php else: ?>
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-12">
        <div class="bg-white rounded-3xl shadow-sm border border-gray-100 p-8 border-t-8 border-t-amber-500">
            <h2 class="text-xl font-bold mb-4 text-gray-800">درخواست‌های نیازمند بررسی</h2>
            <?php 
            $pendingRequests = $pdo->query("SELECT s.*, u.username FROM settlements s JOIN users u ON s.user_id = u.id WHERE s.status = 'pending'")->fetchAll();
            foreach($pendingRequests as $req): ?>
                <div class="border border-amber-200 bg-amber-50 rounded-xl p-4 mb-4">
                    <div class="flex justify-between font-bold mb-2"><span><?php echo $req['username']; ?></span><span><?php echo number_format($req['amount']); ?> تومان</span></div>
                    <div class="flex gap-2">
                        <form method="POST" class="flex-1"><input type="hidden" name="action" value="approve_settlement"><input type="hidden" name="settlement_id" value="<?php echo $req['id']; ?>"><button class="w-full bg-green-500 text-white py-1 rounded">تایید</button></form>
                        <form method="POST" class="flex-1"><input type="hidden" name="action" value="reject_settlement"><input type="hidden" name="settlement_id" value="<?php echo $req['id']; ?>"><button class="w-full bg-red-500 text-white py-1 rounded">رد</button></form>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        <div class="bg-white rounded-3xl shadow-sm border border-gray-100 p-8 border-t-8 border-t-blue-500">
            <h2 class="text-xl font-bold mb-4 text-gray-800">بدهی اپراتورها</h2>
            <table class="w-full text-sm text-right text-gray-500">
                <thead><tr class="bg-gray-100"><th>اپراتور</th><th>بدهی (تومان)</th></tr></thead>
                <tbody>
                    <?php 
                    $operatorDebts = $pdo->query("SELECT u.username, SUM(t.paid_amount - t.profit) as total_debt FROM users u LEFT JOIN transactions t ON u.id = t.user_id AND t.is_settled = 0 AND t.settlement_id IS NULL WHERE u.role = 'operator' GROUP BY u.id")->fetchAll();
                    foreach($operatorDebts as $op): ?>
                        <tr class="border-b"><td><?php echo $op['username']; ?></td><td class="font-bold text-red-600"><?php echo number_format($op['total_debt']); ?></td></tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
<?php endif; ?>

<div class="bg-white rounded-3xl shadow-sm border border-gray-100 p-8 mb-8 border-t-8 border-t-purple-600">
    <h2 class="text-2xl font-bold mb-6 text-gray-800">گزارش‌گیری جامع تسویه‌حساب‌ها</h2>
    
    <form method="GET" class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-8 bg-gray-50 p-6 rounded-2xl border border-gray-200">
        <?php if($isAdmin): ?>
        <div><label class="block text-sm font-bold mb-2">اپراتور</label>
            <select name="report_user" class="w-full border rounded-xl p-2.5 bg-white">
                <option value="">همه</option>
                <?php foreach($operatorsList as $op): ?><option value="<?php echo $op['id']; ?>" <?php echo ($report_user == $op['id']) ? 'selected' : ''; ?>><?php echo $op['username']; ?></option><?php endforeach; ?>
            </select>
        </div>
        <?php endif; ?>
        <div><label class="block text-sm font-bold mb-2">وضعیت</label>
            <select name="report_status" class="w-full border rounded-xl p-2.5 bg-white">
                <option value="all" <?php echo ($report_status == 'all') ? 'selected' : ''; ?>>همه</option>
                <option value="settled" <?php echo ($report_status == 'settled') ? 'selected' : ''; ?>>تسویه شده</option>
                <option value="unsettled" <?php echo ($report_status == 'unsettled') ? 'selected' : ''; ?>>تسویه نشده</option>
            </select>
        </div>
        <div class="flex items-end"><button type="submit" class="w-full bg-purple-600 text-white font-bold py-2.5 rounded-xl">تهیه گزارش</button></div>
    </form>

    <div class="overflow-x-auto">
        <table id="billingReportTable" class="w-full text-sm text-right text-gray-500">
            <thead class="bg-gray-100 text-gray-700">
                <tr>
                    <th class="px-4 py-3">تاریخ</th>
                    <?php if($isAdmin): ?><th class="px-4 py-3">اپراتور</th><?php endif; ?>
                    <th class="px-4 py-3">نام مشتری</th>
                    <th class="px-4 py-3">نام کاربری (اکانت)</th>
                    <th class="px-4 py-3">طرح / حجم</th>
                    <th class="px-4 py-3 text-red-600">بدهی (تومان)</th>
                    <th class="px-4 py-3 text-center">وضعیت</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($reportData as $row): 
                    $rowDebt = $row['paid_amount'] - $row['profit'];
                ?>
                <tr class="border-b hover:bg-gray-50">
                    <td class="px-4 py-3" dir="ltr"><?php echo $row['date_shamsi']; ?></td>
                    <?php if($isAdmin): ?><td class="px-4 py-3 font-bold"><?php echo $row['creator']; ?></td><?php endif; ?>
                    <td class="px-4 py-3 font-bold text-gray-800"><?php echo htmlspecialchars($row['customer_name']); ?></td>
                    <td class="px-4 py-3 font-mono text-blue-600" dir="ltr"><?php echo htmlspecialchars($row['account_username']); ?></td>
                    <td class="px-4 py-3"><?php echo $row['plan']; ?> (<?php echo $row['volume']; ?>G)</td>
                    <td class="px-4 py-3 font-bold text-red-600"><?php echo number_format($rowDebt); ?></td>
                    <td class="px-4 py-3 text-center">
                        <span class="px-3 py-1 rounded-full text-xs font-bold <?php echo ($row['is_settled'] == 1) ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'; ?>">
                            <?php echo ($row['is_settled'] == 1) ? '✅ تسویه شده' : '❌ تسویه نشده'; ?>
                        </span>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot class="bg-gray-800 text-white font-black">
                <tr>
                    <?php $colspan = $isAdmin ? 5 : 4; ?>
                    <th colspan="<?php echo $colspan; ?>" class="px-4 py-3 text-left">مجموع کل گزارش (تومان):</th>
                    <th class="px-4 py-3 text-red-400 text-lg">0</th>
                    <th></th>
                </tr>
            </tfoot>
        </table>
    </div>
</div>

<script src="/vpnet-panel/assets/js/jquery-3.7.0.min.js"></script>
<script src="/vpnet-panel/assets/js/jquery.dataTables.min.js"></script>
<script src="/vpnet-panel/assets/js/dataTables.buttons.min.js"></script>
<script src="/vpnet-panel/assets/js/jszip.min.js"></script>
<script src="/vpnet-panel/assets/js/buttons.html5.min.js"></script>
<script src="/vpnet-panel/assets/js/buttons.print.min.js"></script>

<script>
    document.getElementById('selectAll')?.addEventListener('change', function() {
        document.querySelectorAll('.tx-checkbox').forEach(cb => cb.checked = this.checked);
    });

    $(document).ready(function() {
        // ایندکس ستون مبلغ بدهی در جدول گزارش (اگر ادمین باشد ستون ۵، در غیر این صورت ۴)
        var debtColumnIndex = <?php echo $isAdmin ? 5 : 4; ?>;

        $('#billingReportTable').DataTable({
            destroy: true,
            dom: 'Bfrtip',
            buttons: [
                { extend: 'excelHtml5', text: '📥 دانلود Excel', footer: true },
                { 
                    extend: 'print', text: '🖨️ چاپ / PDF', footer: true, 
                    customize: function ( win ) {
                        $(win.document.body).css( 'direction', 'rtl' ).css('font-family', 'Vazirmatn');
                        $(win.document.body).find('tfoot th').css({'background-color': '#374151', 'color': '#fff'});
                    }
                }
            ],
            "footerCallback": function ( row, data, start, end, display ) {
                var api = this.api();
                var intVal = function ( i ) {
                    return typeof i === 'string' ? i.replace(/[\$,]|,/g, '')*1 : typeof i === 'number' ? i : 0;
                };
                total = api.column( debtColumnIndex, { filter: 'applied'} ).data().reduce( function (a, b) {
                    return intVal(a) + intVal(b);
                }, 0 );
                $( api.column( debtColumnIndex ).footer() ).html(total.toLocaleString());
            },
            language: { "sSearch": "جستجو:", "oPaginate": { "sNext": "بعدی", "sPrevious": "قبلی" } },
            order: [],
            pageLength: 20
        });
    });
</script>

<?php require_once '../includes/footer.php'; ?>