<?php
// admin_financial_report_print.php
// This page generates a print-ready financial report based on URL parameters.

// Ensure session is started.
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Redirect if not logged in OR not an admin/instructor.
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || ($_SESSION['user_role'] !== 'admin' && $_SESSION['user_role'] !== 'instructor')) {
    header("Location: index.php?page=login");
    exit();
}

require_once 'config/database.php';

$message = '';
$is_error = false;
$all_payments = [];
$monthly_summary = [];
$bank_summary = [];
$overall_summary = [
    'total_verified_amount' => 0,
    'total_uploaded_amount' => 0,
    'total_rejected_amount' => 0,
    'total_pending_count' => 0
];
$report_title = '';

$current_user_id = $_SESSION['user_id'];
$current_user_role = $_SESSION['user_role'];

// Retrieve parameters from URL
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : null;
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : null;
$report_section = isset($_GET['section']) ? $_GET['section'] : 'detailed-list'; // Default to detailed list
$filter_course_id = isset($_GET['course_id']) && $_GET['course_id'] !== '' ? $_GET['course_id'] : null;
$filter_modality = isset($_GET['modality']) && $_GET['modality'] !== '' ? $_GET['modality'] : null;
$filter_bank = isset($_GET['bank_name']) && $_GET['bank_name'] !== '' ? $_GET['bank_name'] : null;


// Validate required parameters
if (!$start_date || !$end_date || !preg_match("/^\d{4}-\d{2}-\d{2}$/", $start_date) || !preg_match("/^\d{4}-\d{2}-\d{2}$/", $end_date)) {
    $message = "Invalid or missing date range.";
    $is_error = true;
} elseif (new DateTime($start_date) > new DateTime($end_date)) {
    $message = "Start date cannot be after end date.";
    $is_error = true;
}

try {
    if (!$is_error) {
        // Build the base query for payments with the same joins as the dashboard
        $sql_payments = "
            SELECT
                mp.id AS monthly_payment_id,
                mp.status,
                mp.paid_amount,
                mp.bank_name,
                mp.slip_number,
                mp.payment_date,
                u.full_name AS student_name,
                c.course_name,
                b.batch_name,
                b.modality
            FROM monthly_payments mp
            JOIN course_enrollments ce ON mp.enrollment_id = ce.id
            JOIN users u ON ce.student_id = u.id
            JOIN batches b ON ce.batch_id = b.id
            JOIN courses c ON b.course_id = c.id
            WHERE mp.payment_date BETWEEN ? AND ?
        ";

        $params = [$start_date, $end_date];

        // Add conditional filters
        $where_clauses = [];
        if ($filter_course_id) {
            $where_clauses[] = "c.id = ?";
            $params[] = $filter_course_id;
        }
        if ($filter_modality) {
            $where_clauses[] = "b.modality = ?";
            $params[] = $filter_modality;
        }
        if ($filter_bank) {
            $where_clauses[] = "mp.bank_name = ?";
            $params[] = $filter_bank;
        }
        if ($current_user_role === 'instructor') {
            $where_clauses[] = "b.instructor_id = ?";
            $params[] = $current_user_id;
        }

        if (!empty($where_clauses)) {
            $sql_payments .= " AND " . implode(" AND ", $where_clauses);
        }

        $sql_payments .= " ORDER BY mp.payment_date DESC, mp.uploaded_at DESC";

        $stmt_payments = $pdo->prepare($sql_payments);
        $stmt_payments->execute($params);
        $all_payments = $stmt_payments->fetchAll(PDO::FETCH_ASSOC);

        if (empty($all_payments)) {
            $message = "No payments found for the selected filters.";
        } else {
            // Process payments for summaries if needed
            foreach ($all_payments as $payment) {
                if ($payment['status'] === 'verified') {
                    // Overall Summary
                    $overall_summary['total_verified_amount'] += $payment['paid_amount'];
                    // Monthly Summary
                    $month_key = date('Y-m', strtotime($payment['payment_date']));
                    if (!isset($monthly_summary[$month_key])) {
                        $monthly_summary[$month_key] = 0;
                    }
                    $monthly_summary[$month_key] += $payment['paid_amount'];
                    // Bank Summary
                    if (!empty($payment['bank_name'])) {
                        $bank_name_key = htmlspecialchars($payment['bank_name']);
                        if (!isset($bank_summary[$bank_name_key])) {
                            $bank_summary[$bank_name_key] = 0;
                        }
                        $bank_summary[$bank_name_key] += $payment['paid_amount'];
                    }
                }
            }
            krsort($monthly_summary);
            arsort($bank_summary);
        }
    }
} catch (PDOException $e) {
    $message = "Database error: " . $e->getMessage();
    $is_error = true;
    error_log("Print Report Fetch Error: " . $e->getMessage());
}

// Determine the report title based on the section
switch ($report_section) {
    case 'overall-summary':
        $report_title = 'Overall Financial Summary Report';
        break;
    case 'monthly-summary':
        $report_title = 'Monthly Payments Report';
        break;
    case 'bank-summary':
        $report_title = 'Bank-Wise Payments Report';
        break;
    case 'detailed-list':
    default:
        $report_title = 'Detailed Payments List Report';
        break;
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Print Report - <?php echo htmlspecialchars($report_title); ?></title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; color: #333; }
        .container { max-width: 900px; margin: auto; }
        h1, h2, h3 { color: #1a202c; }
        h1 { font-size: 24px; text-align: center; margin-bottom: 5px; }
        .subtitle { text-align: center; margin-bottom: 20px; font-size: 14px; color: #666; }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; font-size: 12px; text-transform: uppercase; }
        td { font-size: 14px; }
        .total-row td { font-weight: bold; background-color: #e6e6e6; }
        .no-data { text-align: center; color: #777; font-style: italic; margin-top: 20px; }
        .print-button {
            display: block;
            width: 150px;
            margin: 20px auto;
            padding: 10px;
            text-align: center;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        @media print {
            .print-button { display: none; }
            body { margin: 0; }
            .container { max-width: 100%; }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1><?php echo htmlspecialchars($report_title); ?> - ORINSTO LMS</h1>
        <p class="subtitle">
            Report for Period: <?php echo date('F d, Y', strtotime($start_date)); ?> to <?php echo date('F d, Y', strtotime($end_date)); ?>
        </p>

        <?php if ($is_error || empty($all_payments)): ?>
            <div class="no-data">
                <p><?php echo $message; ?></p>
            </div>
        <?php else: ?>
            <?php if ($report_section === 'overall-summary'): ?>
                <table>
                    <thead>
                        <tr>
                            <th>Summary Type</th>
                            <th>Amount</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>Total Verified Payments</td>
                            <td>$<?php echo number_format($overall_summary['total_verified_amount'], 2); ?></td>
                        </tr>
                        <tr>
                            <td>Total Uploaded (Pending)</td>
                            <td>$<?php echo number_format($overall_summary['total_uploaded_amount'], 2); ?></td>
                        </tr>
                        <tr>
                            <td>Total Rejected Payments</td>
                            <td>$<?php echo number_format($overall_summary['total_rejected_amount'], 2); ?></td>
                        </tr>
                    </tbody>
                </table>
            <?php endif; ?>

            <?php if ($report_section === 'monthly-summary'): ?>
                <table>
                    <thead>
                        <tr>
                            <th>Month</th>
                            <th>Total Verified Amount</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($monthly_summary as $month => $amount): ?>
                            <tr>
                                <td><?php echo date('F Y', strtotime($month . '-01')); ?></td>
                                <td>$<?php echo number_format($amount, 2); ?></td>
                            </tr>
                        <?php endforeach; ?>
                        <tr class="total-row">
                            <td>Grand Total</td>
                            <td>$<?php echo number_format(array_sum($monthly_summary), 2); ?></td>
                        </tr>
                    </tbody>
                </table>
            <?php endif; ?>

            <?php if ($report_section === 'bank-summary'): ?>
                <table>
                    <thead>
                        <tr>
                            <th>Bank Name</th>
                            <th>Total Verified Amount</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($bank_summary as $bank => $amount): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($bank); ?></td>
                                <td>$<?php echo number_format($amount, 2); ?></td>
                            </tr>
                        <?php endforeach; ?>
                        <tr class="total-row">
                            <td>Grand Total</td>
                            <td>$<?php echo number_format(array_sum($bank_summary), 2); ?></td>
                        </tr>
                    </tbody>
                </table>
            <?php endif; ?>

            <?php if ($report_section === 'detailed-list'): ?>
                <table>
                    <thead>
                        <tr>
                            <th>Student</th>
                            <th>Course</th>
                            <th>Batch</th>
                            <th>Modality</th>
                            <th>Amount</th>
                            <th>Date Paid</th>
                            <th>Bank</th>
                            <th>Slip No.</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($all_payments as $payment): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($payment['student_name']); ?></td>
                                <td><?php echo htmlspecialchars($payment['course_name']); ?></td>
                                <td><?php echo htmlspecialchars($payment['batch_name']); ?></td>
                                <td><?php echo htmlspecialchars($payment['modality']); ?></td>
                                <td>$<?php echo number_format($payment['paid_amount'], 2); ?></td>
                                <td><?php echo date('M d, Y', strtotime($payment['payment_date'])); ?></td>
                                <td><?php echo htmlspecialchars($payment['bank_name'] ?: 'N/A'); ?></td>
                                <td><?php echo htmlspecialchars($payment['slip_number'] ?: 'N/A'); ?></td>
                                <td style="color: <?php 
                                    if ($payment['status'] === 'verified') echo '#16a34a'; 
                                    elseif ($payment['status'] === 'uploaded') echo '#f97316';
                                    elseif ($payment['status'] === 'rejected') echo '#dc2626';
                                    ?>">
                                    <?php echo htmlspecialchars(ucfirst($payment['status'])); ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        <?php endif; ?>

        <button class="print-button" onclick="window.print()">Print This Report</button>
    </div>
</body>
</html>