<?php
define('SECURE_ACCESS', true);

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

requireLogin();
$currentUser = getCurrentUser();

$eventId = isset($_GET['event_id']) ? (int)$_GET['event_id'] : 0;

if ($eventId <= 0) {
    die("Invalid Event ID.");
}

$targetUserId = $currentUser['id'];
if (isAdmin() && isset($_GET['user_id'])) {
    $targetUserId = (int)$_GET['user_id'];
}

// 1. Fetch Event & Registration details
try {
    $stmt = $pdo->prepare("
        SELECT e.*, r.registered_at, r.base_price, r.gst_rate as reg_gst_rate, r.gst_amount, r.total_payable, u.username as organizer_name, r.id as reg_id
        FROM events e
        JOIN registrations r ON e.id = r.event_id
        LEFT JOIN users u ON e.created_by = u.id
        WHERE e.id = ? AND r.user_id = ?
    ");
    $stmt->execute([$eventId, $targetUserId]);
    $registration = $stmt->fetch();
} catch (PDOException $e) {
    die("Database error: " . $e->getMessage());
}

if (!$registration) {
    die("No registration record found for this event.");
}

if ($registration['payment_type'] !== 'paid') {
    die("Invoices are only generated for paid events.");
}

// 2. Fetch User's KYC details if available for Tax Info
$kyc = null;
try {
    $stmt_kyc = $pdo->prepare("SELECT * FROM kyc_records WHERE user_id = ?");
    $stmt_kyc->execute([$targetUserId]);
    $kyc = $stmt_kyc->fetch();
} catch (PDOException $e) {
    // Ignore
}

// 3. Fetch branding settings
$site_name = 'EventPortal';
$site_tagline = 'Event Management & Corporate Hierarchy';
$site_logo = '';
$site_favicon = '';
$company_address = 'Bandra Kurla Complex, Mumbai, Maharashtra - 400051';
$company_gstin = '27AAACE1234F1Z0';
try {
    $stmt_general = $pdo->query("SELECT key, value FROM system_settings WHERE key IN ('site_name', 'site_tagline', 'site_logo', 'site_favicon', 'company_address', 'company_gstin')");
    $site_cfg = $stmt_general->fetchAll(PDO::FETCH_KEY_PAIR) ?: [];
    $site_name = $site_cfg['site_name'] ?? 'EventPortal';
    $site_tagline = $site_cfg['site_tagline'] ?? 'Event Management & Corporate Hierarchy';
    $site_logo = $site_cfg['site_logo'] ?? '';
    $site_favicon = $site_cfg['site_favicon'] ?? '';
    $company_address = $site_cfg['company_address'] ?? 'Bandra Kurla Complex, Mumbai, Maharashtra - 400051';
    $company_gstin = $site_cfg['company_gstin'] ?? '27AAACE1234F1Z0';
} catch (PDOException $e) {
    // Ignore
}

// 4. Calculate GST splits (CGST & SGST 50% each)
$base_price = (float)$registration['base_price'];
$gst_percent = (float)$registration['reg_gst_rate'];
$gst_amount = (float)$registration['gst_amount'];
$total_payable = (float)$registration['total_payable'];

if ($total_payable <= 0.00) {
    // Fallback for registrations created before database update
    $price = (float)$registration['price'];
    $stmt_gst = $pdo->query("SELECT value FROM system_settings WHERE key = 'gst_rate'");
    $gst_percent = (float)($stmt_gst->fetchColumn() ?: 18.00);
    $gst_rate = $gst_percent / 100.00;

    if (($registration['gst_option'] ?? 'excluding') === 'including') {
        $total_payable = $price;
        $base_price = $total_payable / (1.00 + $gst_rate);
        $gst_amount = $total_payable - $base_price;
    } else {
        $base_price = $price;
        $gst_amount = $base_price * $gst_rate;
        $total_payable = $base_price + $gst_amount;
    }
}

$cgst_rate = $gst_percent / 2.0;
$sgst_rate = $gst_percent / 2.0;
$cgst_amount = $gst_amount / 2.0;
$sgst_amount = $gst_amount / 2.0;

$invoice_number = "INV-" . $registration['id'] . "-" . date('Ymd', strtotime($registration['registered_at']));
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RENENET EDUCARE</title>
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">
    <?php if (!empty($site_favicon)): ?>
        <link rel="icon" type="image/x-icon" href="<?php echo htmlspecialchars($site_favicon); ?>">
    <?php endif; ?>
    <style>
        body {
            background-color: #f8f9fa;
            font-size: 15px;
        }
        .invoice-card {
            background: #fff;
            border-radius: 12px;
            border: 1px solid #e9ecef;
        }
        @media print {
            body {
                background-color: #fff;
                font-size: 12px;
            }
            .invoice-card {
                border: none !important;
                box-shadow: none !important;
                border-radius: 0 !important;
            }
            .no-print {
                display: none !important;
            }
        }
    </style>
</head>
<body class="py-4 py-md-5">

<div class="container-fluid px-md-5">
    <!-- Action buttons -->
    <div class="d-flex justify-content-between align-items-center mb-4 no-print">
        <a href="event/<?php echo $eventId; ?>" class="btn btn-outline-secondary">
            <i class="bi bi-arrow-left me-1"></i> Back to Event
        </a>
        <button onclick="window.print();" class="btn btn-primary">
            <i class="bi bi-printer-fill me-1"></i> Print / Download Invoice
        </button>
    </div>

    <!-- Main Tax Invoice Card -->
    <div class="invoice-card p-4 p-md-5 shadow-sm">
        <div class="row border-bottom pb-4 mb-4 g-4">
            <!-- Company / Logo Branding -->
            <div class="col-12 col-md-6">
                <div class="d-flex align-items-center mb-2">
                    <?php if (!empty($site_logo)): ?>
                        <img src="<?php echo htmlspecialchars($site_logo); ?>" alt="Logo" class="me-2" style="height: 40px; max-width: 180px; object-fit: contain;">
                    <?php else: ?>
                        <i class="bi bi-calendar-event-fill fs-2 text-primary me-2"></i>
                    <?php endif; ?>
                    <h3 class="fw-bold text-dark mb-0"><?php echo htmlspecialchars($site_name); ?></h3>
                </div>
                <p class="text-muted small mb-0"><?php echo htmlspecialchars($site_tagline); ?></p>
            </div>

            <!-- Tax Invoice Details -->
            <div class="col-12 col-md-6 text-md-end">
                <h2 class="text-uppercase fw-bold text-primary tracking-wide mb-1" style="font-size: 1.5rem;">Tax Invoice</h2>
                <div class="text-secondary small">
                    <div class="mb-1"><strong>Invoice No:</strong> <span class="font-monospace text-dark"><?php echo htmlspecialchars($invoice_number); ?></span></div>
                    <div class="mb-1"><strong>Date of Issue:</strong> <span class="text-dark"><?php echo date('d-M-Y H:i', strtotime($registration['registered_at'])); ?></span></div>
                    <div><strong>Place of Supply:</strong> <span class="text-dark">Maharashtra, India (State Code: 27)</span></div>
                </div>
            </div>
        </div>

        <div class="row g-4 mb-4">
            <!-- Billing Details: Supplier -->
            <div class="col-12 col-md-6">
                <h6 class="text-secondary text-uppercase fw-bold font-monospace small mb-2">Billed From (Seller)</h6>
                <div class="text-dark">
                    <strong class="d-block mb-1"><?php echo htmlspecialchars($site_name); ?> Services Ltd.</strong>
                    <div class="small text-secondary">
                        Corporate Office: <?php echo nl2br(htmlspecialchars($company_address)); ?><br>
                        <strong>GSTIN:</strong> <?php echo htmlspecialchars($company_gstin); ?><br>
                        <strong>SAC Code Prefix:</strong> 9996 (Recreational, cultural and sporting services)
                    </div>
                </div>
            </div>

            <!-- Billing Details: Buyer -->
            <div class="col-12 col-md-6">
                <h6 class="text-secondary text-uppercase fw-bold font-monospace small mb-2">Billed To (Buyer)</h6>
                <div class="text-dark">
                    <strong class="d-block mb-1"><?php echo htmlspecialchars($currentUser['username']); ?></strong>
                    <div class="small text-secondary">
                        Email: <?php echo htmlspecialchars($currentUser['email']); ?><br>
                        <?php if ($kyc && !empty($kyc['doc1_number'])): ?>
                            <strong>Aadhaar Card:</strong> XXXX-XXXX-<?php echo substr($kyc['doc1_number'], -4); ?><br>
                        <?php endif; ?>
                        <?php if ($kyc && !empty($kyc['doc2_number'])): ?>
                            <strong>PAN Card:</strong> XXXXX<?php echo substr($kyc['doc2_number'], -5); ?><br>
                        <?php endif; ?>
                        <strong>Verification Status:</strong> 
                        <?php if ($kyc && $kyc['bank_status'] === 'verified'): ?>
                            <span class="text-success fw-bold">Verified Account</span>
                        <?php else: ?>
                            <span class="text-muted">Unverified Account</span>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Invoice Line Items -->
        <div class="table-responsive mb-4">
            <table class="table table-bordered align-middle">
                <thead class="table-light text-secondary font-monospace small">
                    <tr>
                        <th class="text-center" style="width: 8%;">S.No</th>
                        <th>Description of Services</th>
                        <th class="text-center" style="width: 12%;">SAC Code</th>
                        <th class="text-end" style="width: 15%;">Base Value</th>
                        <th class="text-end" style="width: 12%;">CGST</th>
                        <th class="text-end" style="width: 12%;">SGST</th>
                        <th class="text-end" style="width: 18%;">Total Amount</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td class="text-center font-monospace">1</td>
                        <td>
                            <strong class="d-block text-dark"><?php echo htmlspecialchars($registration['title']); ?></strong>
                            <span class="text-muted small">Admission ticket booking confirmation for <?php echo htmlspecialchars($registration['location']); ?>.</span>
                        </td>
                        <td class="text-center font-monospace small">999652</td>
                        <td class="text-end font-monospace">₹<?php echo number_format($base_price, 2); ?></td>
                        <td class="text-end font-monospace small">
                            ₹<?php echo number_format($cgst_amount, 2); ?><br>
                            <span class="text-muted" style="font-size: 0.75rem;"><?php echo number_format($cgst_rate, 1); ?>%</span>
                        </td>
                        <td class="text-end font-monospace small">
                            ₹<?php echo number_format($sgst_amount, 2); ?><br>
                            <span class="text-muted" style="font-size: 0.75rem;"><?php echo number_format($sgst_rate, 1); ?>%</span>
                        </td>
                        <td class="text-end font-monospace fw-bold text-dark">₹<?php echo number_format($total_payable, 2); ?></td>
                    </tr>
                </tbody>
            </table>
        </div>

        <div class="row g-4">
            <div class="col-12 col-md-6">
                <!-- Declaration Terms -->
                <div class="p-3 bg-light rounded-3 border">
                    <h6 class="fw-bold text-secondary mb-2 small font-monospace">GST Compliance Declaration</h6>
                    <p class="mb-0 text-muted" style="font-size: 0.75rem; line-height: 1.4;">
                        This invoice is generated in compliance with the Goods and Services Tax Rules of India. It has been verified and electronically generated. No physical signature is required. CGST & SGST are calculated at a 50/50 ratio on the base ticket supply value.
                    </p>
                </div>
            </div>

            <div class="col-12 col-md-6">
                <!-- Grand Totals table -->
                <table class="table table-borderless table-sm text-secondary mb-0">
                    <tr>
                        <td>Total Taxable Value (Base Price):</td>
                        <td class="text-end font-monospace text-dark">₹<?php echo number_format($base_price, 2); ?></td>
                    </tr>
                    <tr>
                        <td>Central Tax (CGST <?php echo number_format($cgst_rate, 1); ?>%):</td>
                        <td class="text-end font-monospace text-dark">₹<?php echo number_format($cgst_amount, 2); ?></td>
                    </tr>
                    <tr class="border-bottom pb-2">
                        <td>State Tax (SGST <?php echo number_format($sgst_rate, 1); ?>%):</td>
                        <td class="text-end font-monospace text-dark">₹<?php echo number_format($sgst_amount, 2); ?></td>
                    </tr>
                    <tr class="fs-5 fw-bold text-dark">
                        <td class="pt-2 text-primary">Invoice Total (INR):</td>
                        <td class="text-end pt-2 text-success font-monospace">₹<?php echo number_format($total_payable, 2); ?></td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
</div>

</body>
</html>
