<?php
require_once __DIR__ . '/../../classes/Branding.php';
$companyName = Branding::companyName();
$companyLogo = Branding::logoUrl();
$companyLogoFile = Branding::logoFilePath();
$settings = Branding::settings();
$vatPercentage = (float)($settings['vat_percentage'] ?? 17.5);
$vatRate = $vatPercentage / 100;
$profitPercentage = (float)($settings['profit_percentage'] ?? 30.0);
$profitRate = $profitPercentage / 100;
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Branch.php';
require_once __DIR__ . '/../../classes/Quotation.php';

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

$branch = new Branch($conn);
$auth = new Auth($conn);
$quotation = new Quotation($conn);

if (!isset($_SESSION['user_id'])) {
    header('Location: ../../login.php');
    exit();
}


$quotationId = isset($_GET['quotation_id']) ? (int)$_GET['quotation_id'] : null;

if (!$quotationId) {
    header('Location: list_quotations.php?error=' . urlencode('No invoice data found.'));
    exit();
}

$quotationData = $quotation->getQuotationById($quotationId);
if (!$quotationData) {
    header('Location: list_quotations.php?error=' . urlencode('Invoice not found.'));
    exit();
}


$creatorId = $quotationData['created_by'] ?? null;
$creatorName = 'Unknown';
if ($creatorId) {
    $creatorName = $auth->getUserName($creatorId);
    if (!$creatorName) {
        error_log("Failed to retrieve username for user_id: $creatorId in quotation ID: $quotationId");
        $creatorName = 'Unknown';
    }
} else {
    error_log("No created_by field found for quotation ID: $quotationId");
}

$dateTime = new DateTime($_GET['invoice_date']);
$formattedDate = $dateTime->format('Y-m-d');
$validUntil = new DateTime($quotationData['valid_until']);
$formattedValidUntil = $validUntil->format('Y-m-d');

$documentBranch = $branch->getBranchById((int)($quotationData['branch_id'] ?? 0));
$companyDetails = Branding::documentDetailsForBranch($documentBranch);
$companyLogo = $companyDetails['logo'];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars(Branding::pageTitle('Invoice')); ?></title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        .receipt-container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 5px;
            background-color: #fff;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .receipt-header {
            text-align: center;
            margin-bottom: 20px;
            padding-bottom: 20px;
            border-bottom: 1px dashed #ddd;
        }
        .company-logo {
            max-height: 100px;
            width: auto;
            margin-bottom: 15px;
        }
        .receipt-title {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 5px;
        }
        .receipt-subtitle {
            color: #666;
            margin-bottom: 15px;
        }
        .receipt-info {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
        }
        .receipt-info-column {
            flex: 1;
        }
        .receipt-table {
            width: 100%;
            margin-bottom: 20px;
        }
        .receipt-table th {
            background-color: #f5f5f5;
        }
        .receipt-footer {
            text-align: center;
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px dashed #ddd;
            color: #666;
        }
        .receipt-total {
            font-size: 18px;
            font-weight: bold;
        }
        .receipt-notes {
            margin-top: 20px;
            padding: 15px;
            background-color: #f9f9f9;
            border-radius: 5px;
        }
        .receipt-validity {
            margin-top: 20px;
            font-style: italic;
            color: #666;
        }
        @media print {
            .no-print {
                display: none;
            }
            body {
                padding: 0;
                margin: 0;
            }
            .receipt-container {
                box-shadow: none;
                border: none;
                padding: 0;
                width: 100%;
                max-width: 100%;
            }
            .company-logo {
                max-height: 80px;
            }
        }
    </style>
    <link href="/IMS/assets/css/responsive.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-4">
        <div class="alert alert-success mb-4">
            <h4 class="alert-heading">Invoice Generated Successfully!</h4>
            <p>The invoice has been generated and is ready to be printed or saved.</p>
       
	   </div>

        <div class="receipt-container">
            <div class="receipt-header">
                <img src="<?php echo htmlspecialchars($companyLogo); ?>" alt="<?php echo htmlspecialchars($companyName); ?> Logo" class="company-logo">
                <div class="receipt-title">INVOICE</div>
                <div class="receipt-subtitle"><?php echo htmlspecialchars($companyDetails['name']); ?></div>
                <div><?php echo htmlspecialchars($companyDetails['address']); ?></div>
                <div><?php echo htmlspecialchars($companyDetails['phone']); ?></div>
                <div>Email: <?php echo htmlspecialchars($companyDetails['email']); ?> | Web: <?php echo htmlspecialchars($companyDetails['website']); ?></div>
                <div><?php echo htmlspecialchars($companyDetails['tagline']); ?></div>
            </div>

            <div class="receipt-info">
                <div class="receipt-info-column">
                    <p><strong>Invoice #:</strong> <?php echo htmlspecialchars($quotationData['quotation_number']); ?></p>
                    <p><strong>Date:</strong> <?php echo $formattedDate; ?></p>
                    <p><strong>Prepared By:</strong> <?php echo htmlspecialchars($creatorName); ?></p>
                </div>
                <div class="receipt-info-column">
                    <p><strong>Customer:</strong> <?php echo htmlspecialchars($quotationData['customer_name']); ?></p>
                    <p><strong>Contact:</strong> <?php echo htmlspecialchars($quotationData['customer_contact']); ?></p>
                    <p><strong>Due Date:</strong> <?php echo $formattedValidUntil; ?></p>
                </div>
            </div>

            <table class="table table-bordered receipt-table">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Item Name</th>
                        <th>Quantity</th>
                        <th>Unit Price (MWK)</th>
                        <th>Total (MWK)</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $items = $quotationData['items'];
                    foreach ($items as $index => $item) {
                        $itemTotal = $item['quantity'] * $item['unit_price'];
                    ?>
                    <tr>
                        <td><?php echo $index + 1; ?></td>
                        <td><?php echo htmlspecialchars($item['item_name']); ?></td>
                        <td><?php echo htmlspecialchars($item['quantity']); ?></td>
                        <td><?php echo number_format($item['unit_price'], 2); ?></td>
                        <td><?php echo number_format($itemTotal, 2); ?></td>
                    </tr>
                    <?php } ?>
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="4" class="text-end"><strong>Subtotal:</strong></td>
                        <td>MWK <?php echo number_format($quotationData['subtotal'], 2); ?></td>
                    </tr>
                    <tr>
                        <td colspan="4" class="text-end"><strong>VAT (<?php echo htmlspecialchars(number_format($vatPercentage, 2)); ?>%):</strong></td>
                        <td>MWK <?php echo number_format($quotationData['surtax'], 2); ?></td>
                    </tr>
                    <tr>
                        <td colspan="4" class="text-end"><strong>Grand Total:</strong></td>
                        <td class="receipt-total">MWK <?php echo number_format($quotationData['total_amount'], 2); ?></td>
                    </tr>
                </tfoot>
            </table>

            <div class="receipt-notes">
                <h5>Notes:</h5>
                <p><?php echo htmlspecialchars($quotationData['notes'] ?? 'No additional notes provided.'); ?></p>
            </div>

            <div class="receipt-validity">
                <p>Payment is due by <?php echo $formattedValidUntil; ?>.</p>
            </div>

            <div class="receipt-footer">
                <p>Thank you for your business!</p>
                <p>Please contact us at <?php echo htmlspecialchars($companyDetails['phone']); ?> for any inquiries or payment issues.</p>
            </div>
        </div>

        <div class="mt-4 text-center no-print">
            <button class="btn btn-primary" onclick="window.print()">
                <i class="fas fa-print"></i> Print Invoice
            </button>
            <a href="generate_invoice_pdf.php?quotation_id=<?php echo $quotationId; ?>" class="btn btn-secondary">
                <i class="fas fa-download"></i> Download PDF
            </a>
            <a href="send_invoice_email.php?quotation_id=<?php echo $quotationId; ?>" class="btn btn-success">
                <i class="fas fa-envelope"></i> Email Invoice
            </a>
            <a href="list_quotations.php" class="btn btn-outline-secondary">
                <i class="fas fa-arrow-left"></i> Back to Quotation List
            </a>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
