<?php
session_start();
require_once 'includes/config.php';
require_once 'includes/format-currency.php';

if (!isset($_SESSION['nguoi_dung_id']) || $_SESSION['vai_tro'] !== 'admin') {
    die("<h2 style='color:red;text-align:center;padding:50px;'>TRUY CẬP BỊ TỪ CHỐI!</h2>");
}

$thong_bao = '';

// Duyệt chi từ lich_su_affiliate
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['duyet_chi'])) {
    $id = (int)$_POST['id'];
    $stmt = $pdo->prepare("UPDATE lich_su_affiliate SET trang_thai = 'da_thanh_toan' WHERE id = ?");
    if ($stmt->execute([$id])) {
        $thong_bao = ['type' => 'success', 'msg' => '✅ Đã duyệt chi thành công!'];
    }
}

// Thống kê tổng hợp affiliate
$tong_da_thanh_toan = $pdo->query("SELECT COALESCE(SUM(so_tien_hoa_hong),0) FROM lich_su_affiliate WHERE trang_thai='da_thanh_toan'")->fetchColumn();
$tong_cho_duyet     = $pdo->query("SELECT COALESCE(SUM(so_tien_hoa_hong),0) FROM lich_su_affiliate WHERE trang_thai='cho_duyet'")->fetchColumn();
$tong_ban_ghi       = $pdo->query("SELECT COUNT(*) FROM lich_su_affiliate")->fetchColumn();
$tong_doi_tac       = $pdo->query("SELECT COUNT(DISTINCT nguoi_gioi_thieu_id) FROM lich_su_affiliate")->fetchColumn();

// Thống kê doanh số đơn hàng
try { $pdo->exec("CREATE TABLE IF NOT EXISTS don_hang (id INT AUTO_INCREMENT PRIMARY KEY, yeu_cau_id INT, ten_khach_hang VARCHAR(255), so_dien_thoai VARCHAR(20), dich_vu VARCHAR(500), linh_vuc VARCHAR(20) DEFAULT 'nhac', so_luong INT DEFAULT 1, so_tien_goc DECIMAL(15,0) DEFAULT 0, so_tien_thuc_thu DECIMAL(15,0) DEFAULT 0, phuong_thuc_tt VARCHAR(20) DEFAULT 'chuyen_khoan', ma_gioi_thieu VARCHAR(50), nguoi_gioi_thieu_id INT, hoa_hong_da_tinh TINYINT(1) DEFAULT 0, ghi_chu TEXT, ngay_tao TIMESTAMP DEFAULT CURRENT_TIMESTAMP) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"); } catch(Exception $e) {}

$tong_doanh_so      = $pdo->query("SELECT COALESCE(SUM(so_tien_thuc_thu),0) FROM don_hang")->fetchColumn();
$tong_don_hang      = $pdo->query("SELECT COUNT(*) FROM don_hang")->fetchColumn();
$doanh_so_nhac      = $pdo->query("SELECT COALESCE(SUM(so_tien_thuc_thu),0) FROM don_hang WHERE linh_vuc='nhac'")->fetchColumn();
$doanh_so_hoa       = $pdo->query("SELECT COALESCE(SUM(so_tien_thuc_thu),0) FROM don_hang WHERE linh_vuc='hoa'")->fetchColumn();

$danh_sach_don_hang = $pdo->query("
    SELECT d.*, tv.ho_ten AS ten_gioi_thieu
    FROM don_hang d
    LEFT JOIN thanh_vien tv ON d.nguoi_gioi_thieu_id = tv.id
    ORDER BY d.ngay_tao DESC
")->fetchAll();

// Danh sách giao dịch
$danh_sach = $pdo->query("
    SELECT l.*, 
           gt.ho_ten AS ten_gioi_thieu, gt.email AS email_gioi_thieu,
           gd.ho_ten AS ten_duoc_gioi_thieu
    FROM lich_su_affiliate l
    LEFT JOIN thanh_vien gt ON l.nguoi_gioi_thieu_id = gt.id
    LEFT JOIN thanh_vien gd ON l.nguoi_duoc_gioi_thieu_id = gd.id
    ORDER BY FIELD(l.trang_thai,'cho_duyet','da_thanh_toan'), l.ngay_ghi_nhan DESC
")->fetchAll();
?>
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sổ cái Tài chính - Admin</title>
<link rel="stylesheet" href="includes/admin-style.css">
</head>
<body>

<?php require_once 'includes/menu-admin.php'; ?>

<div class="khu-vuc-du-lieu">
    <div class="thanh-tren">
        <span>💰 Kế toán & Sổ cái Tài chính — Affiliate</span>
        <?php if ($tong_cho_duyet > 0): ?>
            <span class="badge-cho">⏳ Chờ duyệt: <?php echo number_format($tong_cho_duyet, 0, ',', '.'); ?> ₫</span>
        <?php endif; ?>
    </div>

    <div class="noi-dung-chinh">
        <?php if ($thong_bao): ?>
            <div class="alert-success"><?php echo $thong_bao['msg']; ?></div>
        <?php endif; ?>

        <!-- THỐNG KÊ TỔNG QUAN -->
        <div class="luoi-tai-chinh" style="grid-template-columns:repeat(4,1fr);margin-bottom:20px;">
            <div class="hop-tai-chinh" style="border-left:5px solid #28a745;">
                <div class="icon">💰</div>
                <div class="so-lieu"><h3 style="color:#28a745;"><?php echo number_format($tong_doanh_so,0,',','.'); ?> ₫</h3><p>Tổng doanh số</p></div>
            </div>
            <div class="hop-tai-chinh" style="border-left:5px solid #1864ab;">
                <div class="icon">📋</div>
                <div class="so-lieu"><h3><?php echo number_format($tong_don_hang,0,',','.'); ?></h3><p>Tổng đơn hàng</p></div>
            </div>
            <div class="hop-tai-chinh" style="border-left:5px solid #ffc107;">
                <div class="icon">⏳</div>
                <div class="so-lieu"><h3 style="color:#d39e00;"><?php echo number_format($tong_cho_duyet,0,',','.'); ?> ₫</h3><p>Hoa hồng chờ duyệt</p></div>
            </div>
            <div class="hop-tai-chinh" style="border-left:5px solid #dc3545;">
                <div class="icon">💸</div>
                <div class="so-lieu"><h3 style="color:#dc3545;"><?php echo number_format($tong_da_thanh_toan,0,',','.'); ?> ₫</h3><p>Hoa hồng đã giải ngân</p></div>
            </div>
        </div>

        <!-- TAB -->
        <div class="thanh-menu-nd">
            <button class="nut-tab-nd dang-chon" onclick="chuyenTabTC('tab-doanh-so',this)">📊 Doanh số Đơn hàng</button>
            <button class="nut-tab-nd" onclick="chuyenTabTC('tab-affiliate',this)">🤝 Hoa hồng Affiliate</button>
        </div>

        <!-- TAB DOANH SỐ -->
        <div id="tab-doanh-so" class="khoi-noi-dung" style="display:block;">
            <div class="khung-bang-header">
                <h3>Danh sách Đơn hàng</h3>
                <div style="display:flex;gap:10px;font-size:13px;">
                    <span style="background:#cce5ff;color:#004085;padding:4px 10px;border-radius:4px;font-weight:bold;">🎵 Âm nhạc: <?php echo number_format($doanh_so_nhac,0,',','.'); ?> ₫</span>
                    <span style="background:#d4edda;color:#155724;padding:4px 10px;border-radius:4px;font-weight:bold;">🎨 Hội họa: <?php echo number_format($doanh_so_hoa,0,',','.'); ?> ₫</span>
                </div>
            </div>
            <div class="bang-cuon"><table class="bang-du-lieu">
                <thead><tr>
                    <th>#</th><th>Khách hàng</th><th>Dịch vụ</th><th>Lĩnh vực</th>
                    <th>Doanh thu</th><th>Thanh toán</th><th>Giới thiệu</th><th>Ngày</th>
                </tr></thead>
                <tbody>
                <?php if (count($danh_sach_don_hang) > 0): ?>
                    <?php foreach ($danh_sach_don_hang as $i => $dh): ?>
                    <tr>
                        <td style="color:#666;"><?php echo $i+1; ?></td>
                        <td>
                            <strong><?php echo htmlspecialchars($dh['ten_khach_hang']); ?></strong><br>
                            <span style="font-size:12px;color:#0056b3;"><?php echo htmlspecialchars($dh['so_dien_thoai']); ?></span>
                        </td>
                        <td style="font-size:13px;"><?php echo htmlspecialchars($dh['dich_vu']); ?></td>
                        <td><?php echo $dh['linh_vuc']=='hoa' ? '<span style="background:#d4edda;color:#155724;padding:2px 8px;border-radius:4px;font-size:12px;font-weight:bold;">🎨 Hội họa</span>' : '<span style="background:#cce5ff;color:#004085;padding:2px 8px;border-radius:4px;font-size:12px;font-weight:bold;">🎵 Âm nhạc</span>'; ?></td>
                        <td class="so-tien"><?php echo number_format($dh['so_tien_thuc_thu'],0,',','.'); ?> ₫</td>
                        <td style="font-size:12px;"><?php $pt=['chuyen_khoan'=>'Chuyển khoản','tien_mat'=>'Tiền mặt','the'=>'Thẻ','khac'=>'Khác']; echo $pt[$dh['phuong_thuc_tt']] ?? $dh['phuong_thuc_tt']; ?></td>
                        <td style="font-size:12px;"><?php echo $dh['ten_gioi_thieu'] ? htmlspecialchars($dh['ten_gioi_thieu']) : '<span style="color:#ccc;">—</span>'; ?></td>
                        <td style="color:#666;font-size:12px;"><?php echo date('d/m/Y H:i', strtotime($dh['ngay_tao'])); ?></td>
                    </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr><td colspan="8" style="text-align:center;padding:30px;color:#999;font-style:italic;">Chưa có đơn hàng nào. Đơn hàng được tạo khi admin xác nhận "Hoàn thành" và nhập doanh thu.</td></tr>
                <?php endif; ?>
                </tbody>
            </table></div>
        </div>

        <!-- TAB AFFILIATE -->
        <div id="tab-affiliate" class="khoi-noi-dung" style="display:none;">
            <div class="khung-bang-header">
                <h3>Danh sách giao dịch Affiliate</h3>
                <div class="filter-tabs">
                    <button class="active" onclick="filterTable('all',this)">Tất cả</button>
                    <button onclick="filterTable('cho_duyet',this)">Chờ duyệt</button>
                    <button onclick="filterTable('da_thanh_toan',this)">Đã thanh toán</button>
                </div>
            </div>
            <div class="bang-cuon"><table class="bang-du-lieu" id="tbl">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Người giới thiệu</th>
                        <th>Người được giới thiệu</th>
                        <th>Hoa hồng</th>
                        <th>Ngày ghi nhận</th>
                        <th>Trạng thái</th>
                        <th>Thao tác</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($danh_sach) > 0): ?>
                        <?php foreach ($danh_sach as $i => $row): ?>
                        <tr data-status="<?php echo $row['trang_thai']; ?>">
                            <td style="color:#666;"><?php echo $i + 1; ?></td>
                            <td>
                                <strong><?php echo htmlspecialchars($row['ten_gioi_thieu'] ?? '—'); ?></strong><br>
                                <span style="font-size:12px;color:#888;"><?php echo htmlspecialchars($row['email_gioi_thieu'] ?? ''); ?></span>
                            </td>
                            <td><?php echo htmlspecialchars($row['ten_duoc_gioi_thieu'] ?? '—'); ?></td>
                            <td class="so-tien"><?php echo number_format($row['so_tien_hoa_hong'], 0, ',', '.'); ?> ₫</td>
                            <td style="color:#666;"><?php echo date('d/m/Y H:i', strtotime($row['ngay_ghi_nhan'])); ?></td>
                            <td>
                                <?php if ($row['trang_thai'] == 'cho_duyet'): ?>
                                    <span class="trang-thai-cho">⏳ Chờ duyệt</span>
                                <?php else: ?>
                                    <span class="trang-thai-xong">✅ Đã thanh toán</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($row['trang_thai'] == 'cho_duyet'): ?>
                                    <form method="POST" style="display:inline;">
                                        <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
                                        <button type="submit" name="duyet_chi" class="nut-duyet">✔ Duyệt chi</button>
                                    </form>
                                <?php else: ?>
                                    <span style="color:#999;font-size:12px;">Hoàn tất</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="7" style="text-align:center;padding:20px;color:#999;">Chưa có giao dịch affiliate nào trong hệ thống.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table></div>
        </div>
    </div>
</div>

<script>
function filterTable(status, btn) {
    document.querySelectorAll('.filter-tabs button').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    document.querySelectorAll('#tbl tbody tr[data-status]').forEach(tr => {
        tr.style.display = (status === 'all' || tr.dataset.status === status) ? '' : 'none';
    });
}
function chuyenTabTC(id, btn) {
    document.getElementById('tab-doanh-so').style.display = 'none';
    document.getElementById('tab-affiliate').style.display = 'none';
    document.getElementById(id).style.display = 'block';
    document.querySelectorAll('.nut-tab-nd').forEach(b => b.classList.remove('dang-chon'));
    btn.classList.add('dang-chon');
}
</script>
</body>
</html>
