<?php
session_start();
include 'layouts/session.php';
include 'layouts/main.php';
include 'layouts/dbconn.php';

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

// Get user role for permissions
$user_id = $_SESSION['user_id'];
$sql_user = "SELECT role_id FROM users WHERE user_id = ?";
$stmt_user = $conn->prepare($sql_user);
$stmt_user->bind_param('i', $user_id);
$stmt_user->execute();
$result_user = $stmt_user->get_result();
$role_id = ($result_user->fetch_assoc())['role_id'];

// Check if user has permission to view financial information
function hasPermission($role_id) {
    // Define roles that can access financial information (adjust as needed)
    $allowed_roles = [1, 2, 4]; // Admin, General Manager, Finance
    return in_array($role_id, $allowed_roles);
}

if (!hasPermission($role_id)) {
    $_SESSION['error_message'] = "You don't have permission to access this page.";
    header('Location: index.php');
    exit();
}

// Check if file number is provided
if (!isset($_GET['file_number']) || empty($_GET['file_number'])) {
    $_SESSION['error_message'] = "No file number provided";
    header('Location: view_proforma_totals.php');
    exit();
}

$file_number = $_GET['file_number'];

// Get file details
$file_query = "SELECT f.*, c.first_name, c.last_name, c.phone_number, c.email as client_email
               FROM files f
               LEFT JOIN customers c ON f.customer = c.customer_id
               WHERE f.file_number = ?";
$file_stmt = $conn->prepare($file_query);
$file_stmt->bind_param('s', $file_number);
$file_stmt->execute();
$file_result = $file_stmt->get_result();

if ($file_result->num_rows === 0) {
    $_SESSION['error_message'] = "File not found";
    header('Location: view_proforma_totals.php');
    exit();
}

$file = $file_result->fetch_assoc();

// Get proforma details
$query = "SELECT p.*, cr.description as cost_description 
          FROM proforma p 
          LEFT JOIN cost_reference cr ON p.cost_code = cr.code
          WHERE p.file_number = ?
          ORDER BY p.category, p.created_at";
$stmt = $conn->prepare($query);
$stmt->bind_param('s', $file_number);
$stmt->execute();
$result = $stmt->get_result();

// Calculate totals
$totals_query = "SELECT SUM(charge) as total_charges, 
                        SUM(vat_amount) as total_vat,
                        MAX(CASE WHEN all_in = 'Yes' THEN all_in_amount ELSE 0 END) as all_in_amount
                 FROM proforma 
                 WHERE file_number = ?";
$totals_stmt = $conn->prepare($totals_query);
$totals_stmt->bind_param('s', $file_number);
$totals_stmt->execute();
$totals_result = $totals_stmt->get_result();
$totals = $totals_result->fetch_assoc();

// Get file ID for links
$file_id_query = "SELECT id FROM files WHERE file_number = ?";
$file_id_stmt = $conn->prepare($file_id_query);
$file_id_stmt->bind_param('s', $file_number);
$file_id_stmt->execute();
$file_id_result = $file_id_stmt->get_result();
$file_id = ($file_id_result->fetch_assoc())['id'];

// Check if invoice exists
$invoice_query = "SELECT invoice_id, invoice_number, total_amount, status, issue_date, due_date 
                 FROM invoices 
                 WHERE file_number = ? 
                 ORDER BY created_at DESC LIMIT 1";
$invoice_stmt = $conn->prepare($invoice_query);
$invoice_stmt->bind_param('s', $file_number);
$invoice_stmt->execute();
$invoice_result = $invoice_stmt->get_result();
$invoice_exists = $invoice_result->num_rows > 0;
$invoice = $invoice_exists ? $invoice_result->fetch_assoc() : null;
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Proforma Details')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .card-header-tab {
            border-bottom: 0;
            background-color: #f8f9fa;
        }
        .info-card {
            margin-bottom: 1.5rem;
        }
        .file-info {
            padding: 1rem;
            background-color: #f8f9fa;
            border-radius: 0.25rem;
            margin-bottom: 1rem;
        }
        .file-info-title {
            font-weight: 600;
            margin-bottom: 0.5rem;
        }
        .file-info-value {
            color: #495057;
        }
        .charges-table th {
            background-color: #f8f9fa;
        }
        .badge-yes {
            background-color: #0ab39c;
            color: #fff;
        }
        .badge-no {
            background-color: #f06548;
            color: #fff;
        }
        .summary-row {
            font-weight: 600;
            background-color: #f8f9fa;
        }
        .grand-total-row {
            font-weight: 600;
            background-color: #eff2f7;
        }
        .all-in-row {
            font-weight: 600;
            background-color: #e6f3ff;
        }
        .print-header {
            display: none;
        }
        .badge-pending {
            background-color: #f7b84b;
            color: #fff;
        }
        .badge-paid {
            background-color: #0ab39c;
            color: #fff;
        }
        .badge-cancelled {
            background-color: #f06548;
            color: #fff;
        }
        @media print {
            .print-header {
                display: block;
                text-align: center;
                margin-bottom: 20px;
            }
            .no-print {
                display: none !important;
            }
            .card {
                border: none !important;
                box-shadow: none !important;
            }
            .card-header, .card-footer {
                background-color: white !important;
                padding: 0.5rem 0 !important;
            }
            body {
                margin: 0;
                padding: 0;
                background: white;
            }
            .container-fluid {
                width: 100% !important;
                padding: 0 !important;
                margin: 0 !important;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page title for normal view -->
                    <div class="no-print">
                        <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Financial', 'title' => 'Proforma Details')); ?>
                    </div>
                    
                    <!-- Print header for printed page -->
                    <div class="print-header">
                        <h2>Proforma Invoice</h2>
                        <h4>File: <?php echo htmlspecialchars($file_number); ?></h4>
                        <p>Generated on: <?php echo date('Y-m-d H:i:s'); ?></p>
                    </div>
                    
                    <!-- Action buttons -->
                    <div class="row mb-4 no-print">
                        <div class="col-12">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <a href="view_proforma_totals.php" class="btn btn-primary">
                                        <i class="ri-arrow-left-line align-middle me-1"></i> Back to List
                                    </a>
                                    <a href="view_file.php?id=<?php echo $file_id; ?>" class="btn btn-info ms-1">
                                        <i class="ri-file-list-line align-middle me-1"></i> View File
                                    </a>
                                </div>
                                <div>
                                    <button type="button" class="btn btn-success" onclick="window.print()">
                                        <i class="ri-printer-line align-middle me-1"></i> Print
                                    </button>
                                    <a href="export_proforma_detail_pdf.php?file_number=<?php echo urlencode($file_number); ?>" class="btn btn-danger ms-1">
                                        <i class="ri-file-pdf-line align-middle me-1"></i> Export PDF
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Main content -->
                    <div class="row">
                        <!-- File Information -->
                        <div class="col-xl-4">
                            <div class="card info-card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">File Information</h5>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <div class="file-info-title">File Number</div>
                                        <div class="file-info-value"><?php echo htmlspecialchars($file_number); ?></div>
                                    </div>
                                    <div class="mb-3">
                                        <div class="file-info-title">Client</div>
                                        <div class="file-info-value"><?php echo htmlspecialchars($file['first_name'] . ' ' . $file['last_name']); ?></div>
                                    </div>
                                    <div class="mb-3">
                                        <div class="file-info-title">Consignee</div>
                                        <div class="file-info-value"><?php echo htmlspecialchars($file['consignee_name']); ?></div>
                                    </div>
                                    <div class="mb-3">
                                        <div class="file-info-title">Destination</div>
                                        <div class="file-info-value"><?php echo htmlspecialchars($file['destination']); ?></div>
                                    </div>
                                    <div class="mb-3">
                                        <div class="file-info-title">Currency</div>
                                        <div class="file-info-value"><?php echo htmlspecialchars($file['currency']); ?></div>
                                    </div>
                                    <div class="mb-3">
                                        <div class="file-info-title">Shipment Type</div>
                                        <div class="file-info-value"><?php echo ($file['local/transit'] == 1) ? 'Local' : 'Transit'; ?></div>
                                    </div>
                                    <div class="mb-3">
                                        <div class="file-info-title">Contact</div>
                                        <div class="file-info-value">
                                            <?php echo htmlspecialchars($file['client_email']); ?><br>
                                            <?php echo htmlspecialchars($file['phone_number'] ?: 'N/A'); ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Financial Summary -->
                            <div class="card info-card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Financial Summary</h5>
                                </div>
                                <div class="card-body">
                                    <table class="table table-borderless">
                                        <tbody>
                                            <tr>
                                                <th>Total Charges:</th>
                                                <td class="text-end"><?php echo $file['currency'] . ' ' . number_format($totals['total_charges'], 2); ?></td>
                                            </tr>
                                            <tr>
                                                <th>Total VAT:</th>
                                                <td class="text-end"><?php echo $file['currency'] . ' ' . number_format($totals['total_vat'], 2); ?></td>
                                            </tr>
                                            <tr class="table-active">
                                                <th>Grand Total:</th>
                                                <td class="text-end"><?php echo $file['currency'] . ' ' . number_format($totals['total_charges'] + $totals['total_vat'], 2); ?></td>
                                            </tr>
                                            <?php if ($totals['all_in_amount'] > 0): ?>
                                            <tr class="table-info">
                                                <th>All-In Amount:</th>
                                                <td class="text-end"><?php echo $file['currency'] . ' ' . number_format($totals['all_in_amount'], 2); ?></td>
                                            </tr>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            
                            <!-- Invoice Information -->
                            <?php if ($invoice_exists): ?>
                            <div class="card info-card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Invoice Information</h5>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <div class="file-info-title">Invoice Number</div>
                                        <div class="file-info-value"><?php echo htmlspecialchars($invoice['invoice_number']); ?></div>
                                    </div>
                                    <div class="mb-3">
                                        <div class="file-info-title">Total Amount</div>
                                        <div class="file-info-value"><?php echo $file['currency'] . ' ' . number_format($invoice['total_amount'], 2); ?></div>
                                    </div>
                                    <div class="mb-3">
                                        <div class="file-info-title">Issue Date</div>
                                        <div class="file-info-value"><?php echo date('Y-m-d', strtotime($invoice['issue_date'])); ?></div>
                                    </div>
                                    <div class="mb-3">
                                        <div class="file-info-title">Due Date</div>
                                        <div class="file-info-value"><?php echo date('Y-m-d', strtotime($invoice['due_date'])); ?></div>
                                    </div>
                                    <div class="mb-3">
                                        <div class="file-info-title">Status</div>
                                        <div class="file-info-value">
                                            <?php if ($invoice['status'] == 'pending'): ?>
                                                <span class="badge badge-pending">Pending</span>
                                            <?php elseif ($invoice['status'] == 'paid'): ?>
                                                <span class="badge badge-paid">Paid</span>
                                            <?php elseif ($invoice['status'] == 'cancelled'): ?>
                                                <span class="badge badge-cancelled">Cancelled</span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    <div class="mt-3 no-print">
                                        <a href="view_invoice.php?id=<?php echo $invoice['invoice_id']; ?>" class="btn btn-sm btn-primary w-100">
                                            <i class="ri-eye-line me-1"></i> View Invoice
                                        </a>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                        
                        <!-- Charges Details -->
                        <div class="col-xl-8">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Proforma Details</h5>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-bordered charges-table">
                                            <thead>
                                                <tr>
                                                    <th>Category</th>
                                                    <th>Cost Code</th>
                                                    <th>Description</th>
                                                    <th>Vatable</th>
                                                    <th class="text-end">Charge</th>
                                                    <th class="text-end">VAT Amount</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php 
                                                $categories = [];
                                                $category_totals = [];
                                                
                                                // First pass: Group by category and calculate subtotals
                                                while ($row = $result->fetch_assoc()) {
                                                    if (!in_array($row['category'], $categories)) {
                                                        $categories[] = $row['category'];
                                                        $category_totals[$row['category']] = [
                                                            'charges' => 0,
                                                            'vat' => 0
                                                        ];
                                                    }
                                                    
                                                    $category_totals[$row['category']]['charges'] += $row['charge'];
                                                    $category_totals[$row['category']]['vat'] += $row['vat_amount'];
                                                }
                                                
                                                // Reset result pointer
                                                $result->data_seek(0);
                                                
                                                // Second pass: Output rows by category
                                                $current_category = '';
                                                while ($row = $result->fetch_assoc()) {
                                                    // If we're starting a new category, add a category header
                                                    if ($current_category != $row['category']) {
                                                        $current_category = $row['category'];
                                                        echo "<tr class='table-light'>";
                                                        echo "<td colspan='6'><strong>" . htmlspecialchars($current_category) . "</strong></td>";
                                                        echo "</tr>";
                                                    }
                                                ?>
                                                <tr>
                                                    <td></td>
                                                    <td><?php echo htmlspecialchars($row['cost_code']); ?></td>
                                                    <td><?php echo htmlspecialchars($row['cost_description'] ?: $row['cost_code']); ?></td>
                                                    <td>
                                                        <?php if ($row['vatable'] == 'Yes'): ?>
                                                            <span class="badge badge-yes">Yes</span>
                                                        <?php else: ?>
                                                            <span class="badge badge-no">No</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td class="text-end"><?php echo number_format($row['charge'], 2); ?></td>
                                                    <td class="text-end"><?php echo number_format($row['vat_amount'], 2); ?></td>
                                                </tr>
                                                <?php
                                                }
                                                
                                                // No data message
                                                if ($result->num_rows === 0) {
                                                    echo "<tr><td colspan='6' class='text-center'>No proforma details found</td></tr>";
                                                }
                                                
                                                // Output category subtotals
                                                foreach ($categories as $category) {
                                                    $charges = $category_totals[$category]['charges'];
                                                    $vat = $category_totals[$category]['vat'];
                                                ?>
                                                <tr class="summary-row">
                                                    <td colspan="4" class="text-end"><strong><?php echo htmlspecialchars($category); ?> Subtotal:</strong></td>
                                                    <td class="text-end"><?php echo number_format($charges, 2); ?></td>
                                                    <td class="text-end"><?php echo number_format($vat, 2); ?></td>
                                                </tr>
                                                <?php
                                                }
                                                ?>
                                                
                                                <!-- Grand total row -->
                                                <tr class="grand-total-row">
                                                    <td colspan="4" class="text-end"><strong>Grand Total:</strong></td>
                                                    <td class="text-end"><strong><?php echo number_format($totals['total_charges'], 2); ?></strong></td>
                                                    <td class="text-end"><strong><?php echo number_format($totals['total_vat'], 2); ?></strong></td>
                                                </tr>
                                                
                                                <!-- Total including VAT -->
                                                <tr class="grand-total-row">
                                                    <td colspan="4" class="text-end"><strong>Total Including VAT:</strong></td>
                                                    <td colspan="2" class="text-end"><strong><?php echo $file['currency'] . ' ' . number_format($totals['total_charges'] + $totals['total_vat'], 2); ?></strong></td>
                                                </tr>
                                                
                                                <!-- All-In amount if present -->
                                                <?php if ($totals['all_in_amount'] > 0): ?>
                                                <tr class="all-in-row">
                                                    <td colspan="4" class="text-end"><strong>All-In Amount:</strong></td>
                                                    <td colspan="2" class="text-end"><strong><?php echo $file['currency'] . ' ' . number_format($totals['all_in_amount'], 2); ?></strong></td>
                                                </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                        </div>
                                </div>
                            </div>

                            <!-- Status and Actions -->
                            <div class="card mt-4 no-print">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Actions</h5>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <?php if (!$invoice_exists): ?>
                                        <div class="col-md-12">
                                            <div class="d-grid gap-2">
                                                <a href="create_invoice.php?file_id=<?php echo $file_id; ?>" class="btn btn-success">
                                                    <i class="ri-add-line align-middle me-1"></i> Create Invoice
                                                </a>
                                            </div>
                                        </div>
                                        <?php else: ?>
                                        <div class="col-md-6">
                                            <div class="d-grid gap-2">
                                                <a href="view_invoice.php?id=<?php echo $invoice['invoice_id']; ?>" class="btn btn-primary">
                                                    <i class="ri-eye-line align-middle me-1"></i> View Invoice
                                                </a>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="d-grid gap-2">
                                                <?php if ($invoice['status'] == 'pending'): ?>
                                                <a href="update_invoice_status.php?id=<?php echo $invoice['invoice_id']; ?>&status=paid" class="btn btn-success" onclick="return confirm('Are you sure you want to mark this invoice as paid?');">
                                                    <i class="ri-check-double-line align-middle me-1"></i> Mark as Paid
                                                </a>
                                                <?php elseif ($invoice['status'] == 'paid'): ?>
                                                <button type="button" class="btn btn-success" disabled>
                                                    <i class="ri-check-double-line align-middle me-1"></i> Invoice Paid
                                                </button>
                                                <?php elseif ($invoice['status'] == 'cancelled'): ?>
                                                <button type="button" class="btn btn-danger" disabled>
                                                    <i class="ri-close-circle-line align-middle me-1"></i> Invoice Cancelled
                                                </button>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Invoice History -->
                            <?php
                            // Check if there are multiple invoices
                            $invoices_query = "SELECT invoice_id, invoice_number, total_amount, status, issue_date 
                                             FROM invoices 
                                             WHERE file_number = ? 
                                             ORDER BY created_at DESC";
                            $invoices_stmt = $conn->prepare($invoices_query);
                            $invoices_stmt->bind_param('s', $file_number);
                            $invoices_stmt->execute();
                            $invoices_result = $invoices_stmt->get_result();
                            
                            if ($invoices_result->num_rows > 1):
                            ?>
                            <div class="card mt-4 no-print">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Invoice History</h5>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-bordered table-hover">
                                            <thead>
                                                <tr>
                                                    <th>Invoice #</th>
                                                    <th>Issue Date</th>
                                                    <th>Amount</th>
                                                    <th>Status</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($invoice_row = $invoices_result->fetch_assoc()): ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($invoice_row['invoice_number']); ?></td>
                                                    <td><?php echo date('Y-m-d', strtotime($invoice_row['issue_date'])); ?></td>
                                                    <td><?php echo $file['currency'] . ' ' . number_format($invoice_row['total_amount'], 2); ?></td>
                                                    <td>
                                                        <?php if ($invoice_row['status'] == 'pending'): ?>
                                                            <span class="badge badge-pending">Pending</span>
                                                        <?php elseif ($invoice_row['status'] == 'paid'): ?>
                                                            <span class="badge badge-paid">Paid</span>
                                                        <?php elseif ($invoice_row['status'] == 'cancelled'): ?>
                                                            <span class="badge badge-cancelled">Cancelled</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <a href="view_invoice.php?id=<?php echo $invoice_row['invoice_id']; ?>" class="btn btn-sm btn-primary">
                                                            <i class="ri-eye-line"></i> View
                                                        </a>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->

            <?php include 'layouts/footer.php'; ?>
        </div>
        <!-- end main content-->
    </div>
    <!-- END layout-wrapper -->

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
</body>
</html>