<?php 
session_start(); // সেশন শুরু করা হলো

// ১. লগইন এবং মাল্টি-টেন্যান্ট সেশন চেক (SaaS Isolation)
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || !isset($_SESSION['isp_id'])) {
    header("Location: login.php");
    exit;
}

$current_isp_id = $_SESSION['isp_id'];

include 'config.php';
date_default_timezone_set('Asia/Dhaka'); 

// ২. ডাটাবেস থেকে কোম্পানির নাম ও আইডি তুলে আনা
$settings_res = mysqli_query($conn, "SELECT company_name, id FROM isps WHERE id = '$current_isp_id' LIMIT 1");

$company_name = 'Our ISP';
$isp_settings = $current_isp_id; 

if ($settings_res && mysqli_num_rows($settings_res) > 0) {
    $isps = mysqli_fetch_assoc($settings_res);
    $company_name = $isps['company_name'] ?? 'Our ISP';
    $isp_settings = $isps['id'];
}

// মাস ও বছর নির্ধারণ (ইনপুট থেকে অথবা কারেন্ট মাস)
$selected_month = isset($_GET['filter_month']) ? $_GET['filter_month'] : date('Y-m');
$safe_month = mysqli_real_escape_string($conn, $selected_month);

// ওই মাসের প্রথম দিন এবং শেষ দিনের টাইম-রেঞ্জ তৈরি (Fast Performance Query-র জন্য)
$start_date = $safe_month . '-01 00:00:00';
$end_date   = date("Y-m-t", strtotime($start_date)) . ' 23:59:59';

// ৩. বিস্তারিত ট্রানজেকশন লিস্ট (Collation Mix Error দূর করতে COLLATE ব্যবহার করা হয়েছে)
$query = "SELECT t.*, c.name 
          FROM transactions t 
          LEFT JOIN customers c ON t.customer_id COLLATE utf8mb4_unicode_ci = c.customer_id COLLATE utf8mb4_unicode_ci AND c.isp_id = '$current_isp_id'
          WHERE t.isp_id = '$current_isp_id' 
          AND t.payment_date >= '$start_date' AND t.payment_date <= '$end_date'
          ORDER BY t.payment_date DESC";
$result = mysqli_query($conn, $query);

// ৪. পেমেন্ট মাধ্যম অনুযায়ী মাসিক সামারি হিসেব (SaaS Isolated)
$summary_query = "SELECT payment_method, SUM(amount) as total 
                  FROM transactions 
                  WHERE isp_id = '$current_isp_id' 
                  AND payment_date >= '$start_date' AND payment_date <= '$end_date'
                  GROUP BY payment_method";
$summary_result = mysqli_query($conn, $summary_query);

// ৫. পুরো মাসের মোট কালেকশন হিসেব
$total_query = "SELECT SUM(amount) as t FROM transactions WHERE isp_id = '$current_isp_id' AND payment_date >= '$start_date' AND payment_date <= '$end_date'";
$total_res = mysqli_query($conn, $total_query);
$total_amount = 0;
if ($total_res) {
    $total_row = mysqli_fetch_assoc($total_res);
    $total_amount = $total_row['t'] ?? 0;
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <title>Monthly Collection Report - <?php echo htmlspecialchars($selected_month); ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap" rel="stylesheet">
    <style>
        :root { --primary: #4f46e5; --success: #10b981; --dark: #1f2937; --warning: #f59e0b; }
        body { font-family: 'Inter', sans-serif; background: #f9fafb; margin: 0; padding: 20px; }
        .container { max-width: 950px; margin: 0 auto; background: white; padding: 30px; border-radius: 12px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
        
        .top-bar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px; }
        .filter-form { display: flex; align-items: center; gap: 10px; background: #f3f4f6; padding: 10px 15px; border-radius: 8px; }
        .filter-form input[type="month"] { padding: 6px; border: 1px solid #ddd; border-radius: 6px; font-family: inherit; }
        
        .header { display: flex; justify-content: space-between; align-items: center; border-bottom: 2px solid #f3f4f6; padding-bottom: 20px; margin-bottom: 20px; }
        h1 { margin: 0; font-size: 22px; color: var(--dark); }
        .total-box { background: #d1fae5; color: #065f46; padding: 12px 25px; border-radius: 10px; font-weight: 700; font-size: 20px; border: 1px solid #10b981; }
        
        table { width: 100%; border-collapse: collapse; margin-top: 10px; }
        th, td { padding: 14px; text-align: left; border-bottom: 1px solid #f3f4f6; font-size: 14px; }
        th { background: #f9fafb; color: #4b5563; text-transform: uppercase; font-size: 11px; letter-spacing: 0.5px; }
        
        .summary-section { margin-top: 40px; width: 300px; margin-left: auto; border: 1px solid #eee; border-radius: 8px; overflow: hidden; }
        .summary-section th { background: #f8fafc; color: var(--dark); font-size: 12px; }
        .summary-title { font-size: 14px; font-weight: 700; margin-bottom: 10px; text-align: right; color: var(--dark); }

        .btn { padding: 9px 16px; border-radius: 6px; text-decoration: none; font-size: 13px; cursor: pointer; border: none; font-weight: 600; display: inline-block; }
        .btn-back { background: #6b7280; color: white; }
        .btn-pdf { background: var(--primary); color: white; }
        .btn-filter { background: var(--dark); color: white; }

        @media print {
            .top-bar, .filter-form, .btn-group { display: none !important; }
            body { background: white; padding: 0; }
            .container { box-shadow: none; max-width: 100%; padding: 0; }
            .summary-section { border: 1px solid #000; }
        }
    </style>
</head>
<body>

<div class="container">
    <div class="top-bar">
        <a href="index.php" class="btn btn-back">← ফিরে যান</a>
        
        <form method="GET" class="filter-form">
            <input type="month" name="filter_month" value="<?php echo htmlspecialchars($selected_month); ?>">
            <button type="submit" class="btn btn-filter">রিপোর্ট দেখুন</button>
        </form>

        <button onclick="window.print()" class="btn btn-pdf">Download PDF / Print</button>
    </div>

    <div class="header">
        <div>
            <h1>মাসিক কালেকশন রিপোর্ট</h1>
            <p style="margin: 5px 0 0; color: #6b7280;">মাস: <strong><?php echo date('F, Y', strtotime($start_date)); ?></strong></p>
        </div>
        <div class="total-box">
            মোট: <?php echo number_format($total_amount, 0); ?> TK
        </div>
    </div>

    <table>
        <thead>
            <tr>
                <th>তারিখ ও সময়</th>
                <th>কাস্টমার আইডি</th>
                <th>নাম</th>
                <th>পেমেন্ট মাধ্যম</th>
                <th>TrxID</th>
                <th style="text-align: right;">পরিমাণ</th>
            </tr>
        </thead>
        <tbody>
            <?php if($result && mysqli_num_rows($result) > 0): ?>
                <?php while($row = mysqli_fetch_assoc($result)): ?>
                <tr>
                    <td><?php echo date('d-m-Y h:i A', strtotime($row['payment_date'])); ?></td>
                    <td><strong><?php echo htmlspecialchars($row['customer_id']); ?></strong></td>
                    <td><?php echo $row['name'] ? htmlspecialchars($row['name']) : '<span style="color:#ef4444; font-size:12px;">Deleted/Unknown</span>'; ?></td>
                    <td><?php echo htmlspecialchars($row['payment_method']); ?></td>
                    <td><?php echo !empty($row['trx_id']) ? htmlspecialchars($row['trx_id']) : '<span style="color:#ccc;">N/A</span>'; ?></td>
                    <td style="text-align: right; font-weight: 600;"><?php echo number_format($row['amount'], 0); ?> TK</td>
                </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr>
                    <td colspan="6" style="text-align:center; padding: 50px; color: #9ca3af;">এই মাসে কোনো কালেকশন ডাটা পাওয়া যায়নি।</td>
                </tr>
            <?php endif; ?>
        </tbody>
    </table>

    <div class="summary-title" style="margin-top: 30px;">পেমেন্ট মাধ্যম অনুযায়ী সারাংশ:</div>
    <table class="summary-section">
        <thead>
            <tr>
                <th>মাধ্যম</th>
                <th style="text-align: right;">মোট পরিমাণ</th>
            </tr>
        </thead>
        <tbody>
            <?php 
            if($summary_result && mysqli_num_rows($summary_result) > 0) {
                while($s_row = mysqli_fetch_assoc($summary_result)) {
                    echo "<tr>
                            <td>".htmlspecialchars($s_row['payment_method'])."</td>
                            <td style='text-align: right; font-weight: 600;'>".number_format($s_row['total'], 0)." TK</td>
                          </tr>";
                }
            } else {
                echo "<tr><td colspan='2' style='text-align:center; padding: 15px; color: #9ca3af;'>ডাটা নেই</td></tr>";
            }
            ?>
            <tr style="background: #f1f5f9;">
                <td><strong>সর্বমোট</strong></td>
                <td style="text-align: right; font-weight: 700; color: var(--primary);"><?php echo number_format($total_amount, 0); ?> TK</td>
            </tr>
        </tbody>
    </table>

    <div style="margin-top: 50px; border-top: 1px dashed #ddd; padding-top: 10px; text-align: center; color: #9ca3af; font-size: 12px;">
        রিপোর্ট তৈরির সময়: <?php echo date('d-m-Y h:i A'); ?> | <?php echo htmlspecialchars($company_name); ?> (ISP ID: <?php echo htmlspecialchars($isp_settings); ?>)
    </div>
</div>

</body>
</html>