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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.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: file_list.php');
    exit();
}

$file_number = $_GET['file_number'];

// Get user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, user_role, full_name, email, role_id FROM users WHERE user_id = $user_id";
$result_user_details = $conn->query($sql_user_details);

if ($result_user_details && $row_user_details = $result_user_details->fetch_assoc()) {
    $username = $row_user_details['username'];
    $user_role = $row_user_details['user_role'];
    $full_name = $row_user_details['full_name'];
    $email = $row_user_details['email'];
    $role_id = $row_user_details['role_id'];
} else {
    // Handle the case if user details are not found
    $_SESSION['error_message'] = "User details not found";
    header('Location: file_list.php');
    exit();
}

// Get file details
$query = "SELECT f.*, c.first_name, c.last_name, c.phone_number, c.address, c.city, c.country, c.postal_code, c.email as client_email
          FROM files f 
          LEFT JOIN customers c ON f.customer = c.customer_id 
          WHERE f.file_number = ?";

$stmt = $conn->prepare($query);
$stmt->bind_param('s', $file_number);
$stmt->execute();
$result = $stmt->get_result();

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

$file = $result->fetch_assoc();
$file_id = $file['id'];

// Get system name from settings
$sql_settings = "SELECT setting_value FROM settings WHERE setting_key = 'system_name'";
$result_settings = $conn->query($sql_settings);
if ($result_settings && $result_settings->num_rows > 0) {
    $row_settings = $result_settings->fetch_assoc();
    $system_name = $row_settings['setting_value'];
} else {
    $system_name = "Freight Management System";
}

// Check user permissions
function hasPermission($role_id, $permission) {
    // Define permissions for different roles
    $permissions = [
        '1' => ['view', 'edit', 'delete', 'approve', 'invoice'], // Admin has all permissions
        '2' => ['view', 'edit', 'approve', 'invoice'], // General Manager
        '3' => ['view', 'edit', 'invoice'], // Operations
        '4' => ['view', 'invoice'], // Finance
        '5' => ['view', 'edit'], // Declaration Officer
        '6' => ['view'], // Shipping Line Clerk
        '7' => ['view'], // Transport Supervisor
    ];
    
    if (isset($permissions[$role_id]) && in_array($permission, $permissions[$role_id])) {
        return true;
    }
    
    return false;
}

$can_invoice = hasPermission($role_id, 'invoice');

// Format date helper function
function formatDate($date) {
    if (empty($date) || $date == '0000-00-00' || $date == '0000-00-00 00:00:00') {
        return 'N/A';
    }
    return date('Y-m-d', strtotime($date));
}

// Check if invoice exists
$invoice_query = "SELECT invoice_id, invoice_number, total_amount, status, issue_date 
                 FROM invoices 
                 WHERE file_number = ? 
                 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;
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'View Proforma Invoice')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .proforma-header {
            margin-bottom: 2rem;
        }
        .company-logo {
            max-height: 80px;
        }
        .invoice-title {
            font-size: 1.5rem;
            font-weight: 600;
            color: #495057;
            text-transform: uppercase;
        }
        .client-details, .company-details {
            margin-bottom: 2rem;
        }
        .section-title {
            font-weight: 600;
            color: #495057;
            border-bottom: 1px solid #e9e9ef;
            padding-bottom: 0.5rem;
            margin-bottom: 1rem;
        }
        .total-row {
            font-weight: 600;
            background-color: #f8f9fa;
        }
        .grand-total-row {
            font-weight: 700;
            background-color: #e9ecef;
        }
        .all-in-row {
            font-weight: 700;
            background-color: #d1e7dd;
            color: #0f5132;
        }
        .print-section {
            text-align: right;
            margin-bottom: 1rem;
        }
        .invoice-footer {
            margin-top: 3rem;
            padding-top: 1rem;
            border-top: 1px solid #e9e9ef;
        }
        .terms-conditions {
            font-size: 0.9rem;
            color: #6c757d;
        }
        @media print {
            .no-print {
                display: none !important;
            }
            .container-fluid {
                width: 100% !important;
                padding: 0 !important;
                margin: 0 !important;
            }
            .card {
                border: none !important;
                box-shadow: none !important;
            }
            body {
                background-color: white !important;
            }
        }
        .vat-badge {
            font-size: 0.75rem;
            padding: 0.2rem 0.4rem;
        }
        .watermark {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) rotate(-45deg);
            font-size: 8rem;
            opacity: 0.05;
            color: #000;
            z-index: 0;
            pointer-events: none;
            white-space: nowrap;
        }
    </style>
</head>

<body>
    <!-- Begin page -->
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <!-- ============================================================== -->
        <!-- Start right Content here -->
        <!-- ============================================================== -->
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Proforma Invoice', 'title' => 'View Proforma')); ?>

                    <div class="print-section no-print">
                        <button type="button" class="btn btn-success" onclick="window.print()">
                            <i class="ri-printer-line align-bottom me-1"></i> Print Proforma
                        </button>
                        <a href="view_file.php?id=<?php echo $file_id; ?>" class="btn btn-primary">
                            <i class="ri-arrow-left-line align-bottom me-1"></i> Back to File
                        </a>
                        <?php if ($can_invoice && !$invoice_exists): ?>
                        <a href="create_invoice.php?file_id=<?php echo $file_id; ?>" class="btn btn-warning">
                            <i class="ri-bill-line align-bottom me-1"></i> Create Invoice
                        </a>
                        <?php elseif ($invoice_exists): ?>
                        <a href="view_invoice.php?id=<?php echo $invoice['invoice_id']; ?>" class="btn btn-info">
                            <i class="ri-eye-line align-bottom me-1"></i> View Invoice
                        </a>
                        <?php endif; ?>
                    </div>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-body position-relative">
                                    <!-- Watermark for proforma -->
                                    <div class="watermark">PROFORMA</div>

                                    <div class="proforma-header row">
                                        <div class="col-sm-6">
                                            <img src="assets/images/logo_header.png" alt="Company Logo" class="company-logo">
                                        </div>
                                        <div class="col-sm-6 text-sm-end">
                                            <h1 class="invoice-title mb-2">PROFORMA INVOICE</h1>
                                            <p class="mb-1"><strong>File Number:</strong> <?php echo htmlspecialchars($file_number); ?></p>
                                            <p class="mb-1"><strong>Date:</strong> <?php echo date('Y-m-d'); ?></p>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-sm-6">
                                            <div class="client-details">
                                                <h5 class="section-title">Client Details</h5>
                                                <p class="mb-1"><strong>Client:</strong> <?php echo htmlspecialchars($file['first_name'] . ' ' . $file['last_name']); ?></p>
                                                <p class="mb-1"><strong>Contact:</strong> <?php echo htmlspecialchars($file['phone_number'] ?? 'N/A'); ?></p>
                                                <p class="mb-1"><strong>Email:</strong> <?php echo htmlspecialchars($file['client_email'] ?? 'N/A'); ?></p>
                                                <p class="mb-0"><strong>Address:</strong> <?php echo nl2br(htmlspecialchars($file['address'] ?? 'N/A')); ?></p>
                                            </div>
                                        </div>
                                        <div class="col-sm-6">
                                            <div class="company-details">
                                                <h5 class="section-title">Company Details</h5>
                                                <p class="mb-1"><strong>Company:</strong> <?php echo htmlspecialchars($system_name); ?></p>
                                                <?php
                                                // Fetch company details from settings
                                                $company_address = '';
                                                $company_tel = '';
                                                
                                                $address_query = "SELECT setting_value FROM settings WHERE setting_key = 'address'";
                                                $address_result = $conn->query($address_query);
                                                if ($address_result && $address_result->num_rows > 0) {
                                                    $address_row = $address_result->fetch_assoc();
                                                    $company_address = $address_row['setting_value'];
                                                }
                                                
                                                $tel_query = "SELECT setting_value FROM settings WHERE setting_key IN ('tel_1', 'tel_2')";
                                                $tel_result = $conn->query($tel_query);
                                                if ($tel_result && $tel_result->num_rows > 0) {
                                                    $phones = [];
                                                    while ($tel_row = $tel_result->fetch_assoc()) {
                                                        if (!empty($tel_row['setting_value'])) {
                                                            $phones[] = $tel_row['setting_value'];
                                                        }
                                                    }
                                                    $company_tel = implode(', ', $phones);
                                                }
                                                ?>
                                                <p class="mb-1"><strong>Address:</strong> <?php echo nl2br(htmlspecialchars($company_address)); ?></p>
                                                <p class="mb-1"><strong>Tel:</strong> <?php echo htmlspecialchars($company_tel); ?></p>
                                                <p class="mb-1"><strong>Currency:</strong> <?php echo htmlspecialchars($file['currency']); ?></p>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row mb-4">
                                        <div class="col-12">
                                            <h5 class="section-title">Shipment Details</h5>
                                            <div class="row">
                                                <div class="col-md-3 mb-2">
                                                    <strong>Consignee:</strong> <?php echo htmlspecialchars($file['consignee_name']); ?>
                                                </div>
                                                <div class="col-md-3 mb-2">
                                                    <strong>BL/AWB:</strong> <?php echo htmlspecialchars($file['obl_no'] ?? 'N/A'); ?>
                                                </div>
                                                <div class="col-md-3 mb-2">
                                                    <strong>Destination:</strong> <?php echo htmlspecialchars($file['destination']); ?>
                                                </div>
                                                <div class="col-md-3 mb-2">
                                                    <strong>Shipment Type:</strong> <?php echo $file['local/transit'] == 1 ? 'Local' : 'Transit'; ?>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-12">
                                            <h5 class="section-title">Invoice Items</h5>
                                            <div class="table-responsive">
                                                <table class="table table-bordered">
                                                    <thead class="table-light">
                                                        <tr>
                                                            <th width="5%">#</th>
                                                            <th width="15%">Category</th>
                                                            <th width="15%">Cost Code</th>
                                                            <th width="30%">Description</th>
                                                            <th width="10%">VAT</th>
                                                            <th width="12%" class="text-end">Amount</th>
                                                            <th width="13%" class="text-end">VAT Amount</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php
                                                        // Fetch proforma items
                                                        $items_query = "SELECT * FROM proforma WHERE file_number = ? ORDER BY id ASC";
                                                        $items_stmt = $conn->prepare($items_query);
                                                        $items_stmt->bind_param('s', $file_number);
                                                        $items_stmt->execute();
                                                        $items_result = $items_stmt->get_result();
                                                        
                                                        $total_amount = 0;
                                                        $total_vat = 0;
                                                        $all_in_amount = 0;
                                                        $currency = $file['currency'];
                                                        $counter = 1;
                                                        
                                                        if ($items_result->num_rows > 0):
                                                            while ($item = $items_result->fetch_assoc()):
                                                                // Track All In amount if exists
                                                                if ($item['all_in'] == 'Yes' && !empty($item['all_in_amount'])) {
                                                                    $all_in_amount = $item['all_in_amount'];
                                                                }
                                                                
                                                                $total_amount += $item['charge'];
                                                                $total_vat += $item['vat_amount'];
                                                        ?>
                                                        <tr>
                                                            <td><?php echo $counter++; ?></td>
                                                            <td><?php echo htmlspecialchars($item['category']); ?></td>
                                                            <td><?php echo htmlspecialchars($item['cost_code']); ?></td>
                                                            <td><?php echo htmlspecialchars($item['cost_description']); ?></td>
                                                            <td>
                                                                <?php if ($item['vatable'] == 'Yes'): ?>
                                                                <span class="badge bg-success vat-badge">Yes</span>
                                                                <?php else: ?>
                                                                <span class="badge bg-light text-dark vat-badge">No</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td class="text-end"><?php echo $currency . ' ' . number_format($item['charge'], 2); ?></td>
                                                            <td class="text-end"><?php echo $currency . ' ' . number_format($item['vat_amount'], 2); ?></td>
                                                        </tr>
                                                        <?php 
                                                            endwhile; 
                                                        else:
                                                        ?>
                                                        <tr>
                                                            <td colspan="7" class="text-center">No items found</td>
                                                        </tr>
                                                        <?php endif; ?>
                                                    </tbody>
                                                    <tfoot>
                                                        <tr class="total-row">
                                                            <td colspan="5" class="text-end">Subtotal:</td>
                                                            <td class="text-end"><?php echo $currency . ' ' . number_format($total_amount, 2); ?></td>
                                                            <td class="text-end"><?php echo $currency . ' ' . number_format($total_vat, 2); ?></td>
                                                        </tr>
                                                        <tr class="grand-total-row">
                                                            <td colspan="5" class="text-end">Total (incl. VAT):</td>
                                                            <td colspan="2" class="text-end"><?php echo $currency . ' ' . number_format($total_amount + $total_vat, 2); ?></td>
                                                        </tr>
                                                        <?php if ($all_in_amount > 0): ?>
                                                        <tr class="all-in-row">
                                                            <td colspan="5" class="text-end">All-In Amount:</td>
                                                            <td colspan="2" class="text-end"><?php echo $currency . ' ' . number_format($all_in_amount, 2); ?></td>
                                                        </tr>
                                                        <?php endif; ?>
                                                    </tfoot>
                                                </table>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-12">
                                            <div class="invoice-footer">
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <div class="terms-conditions">
                                                            <h6>Terms & Conditions</h6>
                                                            <ol class="ps-3 mb-0">
                                                                <li>This is a proforma invoice and not a final bill.</li>
                                                                <li>All payments are to be made in the currency specified.</li>
                                                                <li>This proforma is valid for 15 days from the issue date.</li>
                                                                <li>Actual charges may vary based on final services rendered.</li>
                                                            </ol>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6 text-md-end">
                                                        <div class="mt-4 pt-2">
                                                            <strong>Authorized Signature</strong>
                                                            <div class="mt-3 pt-3 border-top">
                                                                <?php echo htmlspecialchars($full_name); ?>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </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>