<?php
require_once 'config/config.php';
require_once 'config/database.php';
require_once 'models/Student.php';

requireLogin();

// Include TCPDF library (you'll need to download and include this)
// For now, I'll create a simple HTML to PDF solution
require_once 'vendor/autoload.php'; // If using Composer

$database = new Database();
$db = $database->getConnection();

// Get fee deposit ID from URL
$deposit_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($deposit_id <= 0) {
    die('Invalid deposit ID');
}

// Get fee deposit details
$query = "SELECT fh.*, s.student_name, s.fathers_name, s.mothers_name, s.contact_number, 
                 s.email, s.address, s.student_id, s.total_fee
          FROM fee_history fh 
          JOIN students s ON fh.student_id = s.id 
          WHERE fh.id = ?";
$stmt = $db->prepare($query);
$stmt->execute([$deposit_id]);
$deposit = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$deposit) {
    die('Deposit record not found');
}

// Get total deposited amount for this student
$total_deposited_query = "SELECT COALESCE(SUM(amount), 0) as total_deposited 
                          FROM fee_history 
                          WHERE student_id = ?";
$total_stmt = $db->prepare($total_deposited_query);
$total_stmt->execute([$deposit['student_id']]);
$total_deposited = $total_stmt->fetch(PDO::FETCH_ASSOC)['total_deposited'];

// Generate invoice number
$invoice_number = 'INV-' . date('Y') . '-' . str_pad($deposit_id, 4, '0', STR_PAD_LEFT);

// School/Institution details (customize these)
$school_name = "Student Management System";
$school_address = "Your School Address, City, State, PIN";
$school_contact = "Phone: +91-XXXXXXXXXX | Email: info@yourschool.com";
$gstin = "22AAAAA0000A1Z5"; // Replace with actual GSTIN
$bank_name = "Your Bank Name";
$account_number = "XXXXXXXXXXXXXX";
$ifsc_code = "XXXX0000000";

// Create HTML content for PDF
$html = '
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            font-size: 12px;
            line-height: 1.4;
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
            border-bottom: 2px solid #333;
            padding-bottom: 20px;
        }
        .school-name {
            font-size: 24px;
            font-weight: bold;
            color: #333;
            margin-bottom: 10px;
        }
        .school-address {
            font-size: 14px;
            color: #666;
            margin-bottom: 5px;
        }
        .school-contact {
            font-size: 12px;
            color: #666;
        }
        .invoice-details {
            display: flex;
            justify-content: space-between;
            margin-bottom: 30px;
        }
        .invoice-info {
            text-align: right;
        }
        .invoice-title {
            font-size: 20px;
            font-weight: bold;
            color: #333;
            margin-bottom: 10px;
        }
        .party-details {
            margin-bottom: 30px;
        }
        .party-section {
            margin-bottom: 15px;
        }
        .party-label {
            font-weight: bold;
            display: inline-block;
            width: 120px;
        }
        .items-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        .items-table th,
        .items-table td {
            border: 1px solid #333;
            padding: 8px;
            text-align: left;
        }
        .items-table th {
            background-color: #f5f5f5;
            font-weight: bold;
        }
        .items-table .text-right {
            text-align: right;
        }
        .items-table .text-center {
            text-align: center;
        }
        .totals {
            margin-left: auto;
            width: 300px;
        }
        .total-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 5px;
            padding: 5px 0;
        }
        .total-label {
            font-weight: bold;
        }
        .grand-total {
            border-top: 2px solid #333;
            padding-top: 10px;
            font-size: 16px;
            font-weight: bold;
        }
        .bank-details {
            margin-top: 30px;
            margin-bottom: 20px;
        }
        .bank-details h4 {
            margin-bottom: 10px;
            color: #333;
        }
        .terms {
            margin-top: 30px;
        }
        .terms h4 {
            margin-bottom: 10px;
            color: #333;
        }
        .terms ol {
            margin: 0;
            padding-left: 20px;
        }
        .footer {
            margin-top: 40px;
            text-align: center;
        }
        .signature {
            margin-top: 30px;
            text-align: right;
        }
        .seal {
            width: 100px;
            height: 100px;
            border: 2px solid #333;
            border-radius: 50%;
            margin: 20px auto;
            display: flex;
            align-items: center;
            justify-content: center;
            text-align: center;
            font-size: 10px;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="school-name">' . $school_name . '</div>
        <div class="school-address">' . $school_address . '</div>
        <div class="school-contact">' . $school_contact . '</div>
    </div>

    <div class="invoice-details">
        <div class="party-details">
            <div class="party-section">
                <span class="party-label">Party Name:</span> ' . htmlspecialchars($deposit['student_name']) . '
            </div>
            <div class="party-section">
                <span class="party-label">Father\'s Name:</span> ' . htmlspecialchars($deposit['fathers_name']) . '
            </div>
            <div class="party-section">
                <span class="party-label">Student ID:</span> ' . htmlspecialchars($deposit['student_id']) . '
            </div>
            <div class="party-section">
                <span class="party-label">Contact:</span> ' . htmlspecialchars($deposit['contact_number']) . '
            </div>
            <div class="party-section">
                <span class="party-label">Address:</span> ' . htmlspecialchars($deposit['address']) . '
            </div>
        </div>
        
        <div class="invoice-info">
            <div class="invoice-title">FEE DEPOSIT RECEIPT</div>
            <div><strong>Receipt No:</strong> ' . $invoice_number . '</div>
            <div><strong>Date:</strong> ' . date('d-m-Y', strtotime($deposit['payment_date'])) . '</div>
            <div><strong>GSTIN:</strong> ' . $gstin . '</div>
        </div>
    </div>

    <table class="items-table">
        <thead>
            <tr>
                <th>Description</th>
                <th>Student ID</th>
                <th>Payment Date</th>
                <th>Payment Method</th>
                <th class="text-right">Amount</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Fee Deposit - ' . htmlspecialchars($deposit['student_name']) . '</td>
                <td class="text-center">' . htmlspecialchars($deposit['student_id']) . '</td>
                <td class="text-center">' . date('d-m-Y', strtotime($deposit['payment_date'])) . '</td>
                <td class="text-center">' . htmlspecialchars($deposit['payment_method']) . '</td>
                <td class="text-right">₹' . number_format($deposit['amount'], 2) . '</td>
            </tr>
        </tbody>
    </table>

    <div class="totals">
        <div class="total-row">
            <span class="total-label">Total Fee:</span>
            <span>₹' . number_format($deposit['total_fee'], 2) . '</span>
        </div>
        <div class="total-row">
            <span class="total-label">Total Deposited:</span>
            <span>₹' . number_format($total_deposited, 2) . '</span>
        </div>
        <div class="total-row">
            <span class="total-label">This Deposit:</span>
            <span>₹' . number_format($deposit['amount'], 2) . '</span>
        </div>
        <div class="total-row">
            <span class="total-label">Pending Amount:</span>
            <span>₹' . number_format($deposit['total_fee'] - $total_deposited, 2) . '</span>
        </div>
        <div class="total-row grand-total">
            <span class="total-label">Amount Received:</span>
            <span>₹' . number_format($deposit['amount'], 2) . '</span>
        </div>
    </div>

    <div class="bank-details">
        <h4>Bank Details:</h4>
        <div><strong>Bank Name:</strong> ' . $bank_name . '</div>
        <div><strong>Account Number:</strong> ' . $account_number . '</div>
        <div><strong>IFSC Code:</strong> ' . $ifsc_code . '</div>
    </div>

    <div class="terms">
        <h4>Terms & Conditions:</h4>
        <ol>
            <li>All Subject to Local Jurisdiction.</li>
            <li>This is a computer generated receipt.</li>
            <li>Please keep this receipt for your records.</li>
            <li>E.& O.E.</li>
        </ol>
    </div>

    <div class="footer">
        <div class="seal">
            ' . strtoupper($school_name) . '<br>
            FEE RECEIPT
        </div>
        <div class="signature">
            <strong>For - ' . $school_name . '</strong><br><br>
            <div style="border-top: 1px solid #333; width: 200px; margin-left: auto;">
                Authorized Signature
            </div>
        </div>
    </div>
</body>
</html>';

// Generate PDF using DomPDF (alternative to TCPDF)
try {
    // If you have DomPDF installed via Composer
    $dompdf = new \Dompdf\Dompdf();
    $dompdf->loadHtml($html);
    $dompdf->setPaper('A4', 'portrait');
    $dompdf->render();
    
    // Output the PDF
    $dompdf->stream('fee_receipt_' . $invoice_number . '.pdf', array('Attachment' => 0));
    
} catch (Exception $e) {
    // Fallback: Generate HTML version
    echo $html;
}
?>
