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

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

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

$file_id = intval($_GET['file_id']);

// 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'];
}

// 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;
}

// Verify user has invoice permissions
if (!hasPermission($role_id, 'invoice')) {
    $_SESSION['error_message'] = "You don't have permission to create invoices";
    header('Location: file_list.php');
    exit();
}

// Get file details
$query = "SELECT f.*, c.first_name as customer_name, c.customer_id, c.email as customer_email
          FROM files f 
          LEFT JOIN customers c ON f.customer = c.customer_id 
          WHERE f.id = ?";

$stmt = $conn->prepare($query);
$stmt->bind_param('i', $file_id);
$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_number = $file['file_number'];
$customer_id = $file['customer_id'];
$customer_name = $file['customer_name'];
$customer_email = $file['customer_email'];

// Check if an invoice already exists for this file
$invoice_check_query = "SELECT invoice_id, invoice_number FROM invoices WHERE file_number = ? LIMIT 1";
$invoice_check_stmt = $conn->prepare($invoice_check_query);
$invoice_check_stmt->bind_param('s', $file_number);
$invoice_check_stmt->execute();
$invoice_check_result = $invoice_check_stmt->get_result();

if ($invoice_check_result->num_rows > 0) {
    $existing_invoice = $invoice_check_result->fetch_assoc();
    $_SESSION['warning_message'] = "An invoice already exists for this file. Invoice Number: " . $existing_invoice['invoice_number'];
}

// Get charges details
$charges_query = "SELECT * FROM charges WHERE file_number = ?";
$charges_stmt = $conn->prepare($charges_query);
$charges_stmt->bind_param('s', $file_number);
$charges_stmt->execute();
$charges_result = $charges_stmt->get_result();
$charges = $charges_result->fetch_assoc();

// Get pre-proforma data if available
$proforma_query = "SELECT * FROM pre_proforma WHERE file_number = ? ORDER BY id ASC";
$proforma_stmt = $conn->prepare($proforma_query);
$proforma_stmt->bind_param('s', $file_number);
$proforma_stmt->execute();
$proforma_result = $proforma_stmt->get_result();
$proforma_items = [];

if ($proforma_result->num_rows > 0) {
    while ($row = $proforma_result->fetch_assoc()) {
        $proforma_items[] = $row;
    }
}

// Get next invoice number
function getNextInvoiceNumber($conn) {
    $year = date('y');
    $query = "SELECT MAX(invoice_number) as last_number FROM invoices 
              WHERE invoice_number LIKE 'RF/INV/%/$year'";
    $result = $conn->query($query);
    $row = $result->fetch_assoc();
    
    if ($row['last_number']) {
        // Extract the numeric part
        $parts = explode('/', $row['last_number']);
        $number = intval($parts[2]);
        $next_number = $number + 1;
    } else {
        $next_number = 1;
    }
    
    // Format with leading zeros (3 digits)
    $formatted_number = sprintf("%03d", $next_number);
    return "RF/INV/$formatted_number/$year";
}

$next_invoice_number = getNextInvoiceNumber($conn);

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Start transaction
    $conn->begin_transaction();
    
    try {
        $invoice_number = $_POST['invoice_number'];
        $total_amount = 0;
        $issue_date = date('Y-m-d');
        $due_date = date('Y-m-d', strtotime('+30 days'));
        
        if (isset($_POST['due_date']) && !empty($_POST['due_date'])) {
            $due_date = date('Y-m-d', strtotime($_POST['due_date']));
        }
        
        $notes = $_POST['notes'] ?? '';
        $status = 'pending';
        
        // Prepare item arrays
        $item_names = $_POST['item_name'] ?? [];
        $item_descriptions = $_POST['item_description'] ?? [];
        $item_quantities = $_POST['item_quantity'] ?? [];
        $item_prices = $_POST['item_price'] ?? [];
        
        // Calculate total amount
        for ($i = 0; $i < count($item_names); $i++) {
            if (empty($item_names[$i])) continue;
            
            $quantity = intval($item_quantities[$i]);
            $price = floatval($item_prices[$i]);
            $total_amount += ($quantity * $price);
        }
        
        // Insert invoice header
        $invoice_query = "INSERT INTO invoices (
            user_id, customer_id, invoice_number, file_number,
            total_amount, issue_date, due_date, notes, status
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        $invoice_stmt = $conn->prepare($invoice_query);
        $invoice_stmt->bind_param(
            'iissdssss',
            $user_id,
            $customer_id,
            $invoice_number,
            $file_number,
            $total_amount,
            $issue_date,
            $due_date,
            $notes,
            $status
        );
        
        if (!$invoice_stmt->execute()) {
            throw new Exception("Error creating invoice: " . $invoice_stmt->error);
        }
        
        $invoice_id = $conn->insert_id;
        
        // Insert invoice items (if using a separate table for line items)
        // For the basic version, we'll store them in JSON in the main invoice
        
        // Update file table to mark it as invoiced
        $update_file_query = "UPDATE files SET invoice = 1 WHERE id = ?";
        $update_file_stmt = $conn->prepare($update_file_query);
        $update_file_stmt->bind_param('i', $file_id);
        $update_file_stmt->execute();
        
        // Create notification
        $notif_message = "Invoice {$invoice_number} created for file {$file_number} by {$username}.";
        $notif_query = "INSERT INTO notifications (file_id, file_number, notif_message, notif_message_id, created_at) 
                        VALUES (?, ?, ?, 2, NOW())";
        
        $notif_stmt = $conn->prepare($notif_query);
        $notif_stmt->bind_param('iss', $file_id, $file_number, $notif_message);
        $notif_stmt->execute();
        
        // Commit the transaction
        $conn->commit();
        
        $_SESSION['success_message'] = "Invoice created successfully! Invoice Number: $invoice_number";
        header("Location: view_invoice.php?id=$invoice_id");
        exit();
        
    } catch (Exception $e) {
        // Rollback the transaction
        $conn->rollback();
        $_SESSION['error_message'] = "Error creating invoice: " . $e->getMessage();
    }
}
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Create Invoice')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .invoice-header {
            margin-bottom: 2rem;
        }
        .item-row {
            margin-bottom: 1rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid #eee;
        }
        .invoice-total {
            font-size: 1.2rem;
            font-weight: 600;
        }
        .required-field::after {
            content: " *";
            color: red;
        }
        .invoice-summary {
            background-color: #f8f9fa;
            padding: 1.5rem;
            border-radius: 0.25rem;
            margin-top: 2rem;
        }
        .delete-item-btn {
            margin-top: 2rem;
        }
        #addItemBtn {
            margin-top: 1rem;
        }
    </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' => 'Invoicing', 'title' => 'Create Invoice')); ?>

                    <?php if (isset($_SESSION['error_message'])): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <?php echo $_SESSION['error_message']; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    <?php unset($_SESSION['error_message']); ?>
                    <?php endif; ?>

                    <?php if (isset($_SESSION['warning_message'])): ?>
                    <div class="alert alert-warning alert-dismissible fade show" role="alert">
                        <?php echo $_SESSION['warning_message']; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    <?php unset($_SESSION['warning_message']); ?>
                    <?php endif; ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Create Invoice for Shipment #<?php echo htmlspecialchars($file_number); ?></h4>
                                    <div class="flex-shrink-0">
                                        <a href="view_file.php?id=<?php echo $file_id; ?>" class="btn btn-light btn-sm">
                                            <i class="ri-arrow-left-line align-bottom"></i> Back to File
                                        </a>
                                    </div>
                                </div>
                                
                                <div class="card-body">
                                    <form method="POST" action="">
                                        <div class="row invoice-header">
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <label for="invoice_number" class="form-label required-field">Invoice Number</label>
                                                    <input type="text" class="form-control" id="invoice_number" name="invoice_number" value="<?php echo htmlspecialchars($next_invoice_number); ?>" required>
                                                </div>
                                                <div class="mb-3">
                                                    <label for="customer_name" class="form-label">Customer</label>
                                                    <input type="text" class="form-control" id="customer_name" value="<?php echo htmlspecialchars($customer_name); ?>" readonly>
                                                </div>
                                                <div class="mb-3">
                                                    <label for="file_number" class="form-label">File Number</label>
                                                    <input type="text" class="form-control" id="file_number" value="<?php echo htmlspecialchars($file_number); ?>" readonly>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <label for="issue_date" class="form-label">Issue Date</label>
                                                    <input type="date" class="form-control" id="issue_date" value="<?php echo date('Y-m-d'); ?>" readonly>
                                                </div>
                                                <div class="mb-3">
                                                    <label for="due_date" class="form-label required-field">Due Date</label>
                                                    <input type="date" class="form-control" id="due_date" name="due_date" value="<?php echo date('Y-m-d', strtotime('+30 days')); ?>" required>
                                                </div>
                                                <div class="mb-3">
                                                    <label for="currency" class="form-label">Currency</label>
                                                    <input type="text" class="form-control" id="currency" value="<?php echo htmlspecialchars($file['currency'] ?? '$'); ?>" readonly>
                                                </div>
                                            </div>
                                        </div>

                                        <h5 class="border-bottom pb-2 mb-4">Invoice Items</h5>
                                        
                                        <div id="invoice-items">
                                            <?php if (!empty($proforma_items)): ?>
                                                <!-- Populate from pre-proforma if available -->
                                                <?php foreach ($proforma_items as $index => $item): 
                                                    if ($item['charge'] <= 0) continue; // Skip zero or negative charges
                                                ?>
                                                <div class="row item-row">
                                                    <div class="col-md-3">
                                                        <label class="form-label required-field">Item Name</label>
                                                        <input type="text" class="form-control item-name" name="item_name[]" 
                                                            value="<?php echo htmlspecialchars($item['cost_description'] ?: $item['cost_code']); ?>" required>
                                                    </div>
                                                    <div class="col-md-4">
                                                        <label class="form-label">Description</label>
                                                        <input type="text" class="form-control" name="item_description[]" 
                                                            value="<?php echo htmlspecialchars($item['category'] . ' charge'); ?>">
                                                    </div>
                                                    <div class="col-md-2">
                                                        <label class="form-label required-field">Quantity</label>
                                                        <input type="number" min="1" class="form-control item-quantity" name="item_quantity[]" 
                                                            value="1" required onchange="calculateTotal()">
                                                    </div>
                                                    <div class="col-md-2">
                                                        <label class="form-label required-field">Price</label>
                                                        <input type="number" step="0.01" min="0" class="form-control item-price" 
                                                            name="item_price[]" value="<?php echo htmlspecialchars($item['charge']); ?>" 
                                                            required onchange="calculateTotal()">
                                                    </div>
                                                    <div class="col-md-1">
                                                        <button type="button" class="btn btn-danger btn-sm delete-item-btn" onclick="removeItem(this)">
                                                            <i class="ri-delete-bin-line"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                                <?php endforeach; ?>
                                            <?php else: ?>
                                                <!-- Default empty item if no pre-proforma -->
                                                <div class="row item-row">
                                                    <div class="col-md-3">
                                                        <label class="form-label required-field">Item Name</label>
                                                        <input type="text" class="form-control item-name" name="item_name[]" required>
                                                    </div>
                                                    <div class="col-md-4">
                                                        <label class="form-label">Description</label>
                                                        <input type="text" class="form-control" name="item_description[]">
                                                    </div>
                                                    <div class="col-md-2">
                                                        <label class="form-label required-field">Quantity</label>
                                                        <input type="number" min="1" class="form-control item-quantity" name="item_quantity[]" 
                                                            value="1" required onchange="calculateTotal()">
                                                    </div>
                                                    <div class="col-md-2">
                                                        <label class="form-label required-field">Price</label>
                                                        <input type="number" step="0.01" min="0" class="form-control item-price" 
                                                            name="item_price[]" required onchange="calculateTotal()">
                                                    </div>
                                                    <div class="col-md-1">
                                                        <button type="button" class="btn btn-danger btn-sm delete-item-btn" onclick="removeItem(this)">
                                                            <i class="ri-delete-bin-line"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                            <?php endif; ?>
                                        </div>

                                        <div class="row">
                                            <div class="col-12 text-end">
                                                <button type="button" id="addItemBtn" class="btn btn-sm btn-info" onclick="addItem()">
                                                    <i class="ri-add-line align-bottom me-1"></i> Add Item
                                                </button>
                                            </div>
                                        </div>

                                        <div class="row invoice-summary">
                                            <div class="col-md-8">
                                                <div class="mb-3">
                                                    <label for="notes" class="form-label">Notes / Terms</label>
                                                    <textarea class="form-control" id="notes" name="notes" rows="3" 
                                                        placeholder="Payment terms, bank details, or additional notes"><?php echo isset($notes) ? htmlspecialchars($notes) : "Payment due within 30 days.\nBank details: [Your bank details]\nThank you for your business!"; ?></textarea>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="card border">
                                                    <div class="card-body">
                                                        <div class="d-flex justify-content-between mb-2">
                                                            <span>Subtotal:</span>
                                                            <span id="subtotal">0.00</span>
                                                        </div>
                                                        <div class="d-flex justify-content-between border-top pt-2 mb-2">
                                                            <span>Total:</span>
                                                            <span id="total" class="invoice-total">0.00</span>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="row mt-4">
                                            <div class="col-12 d-flex justify-content-between">
                                                <a href="view_file.php?id=<?php echo $file_id; ?>" class="btn btn-secondary">
                                                    <i class="ri-arrow-left-line align-bottom me-1"></i> Cancel
                                                </a>
                                                <button type="submit" class="btn btn-primary">
                                                    <i class="ri-bill-line align-bottom me-1"></i> Create Invoice
                                                </button>
                                            </div>
                                        </div>
                                    </form>
                                </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>
        function addItem() {
            const itemsContainer = document.getElementById('invoice-items');
            const newItem = document.createElement('div');
            newItem.className = 'row item-row';
            newItem.innerHTML = `
                <div class="col-md-3">
                    <label class="form-label required-field">Item Name</label>
                    <input type="text" class="form-control item-name" name="item_name[]" required>
                </div>
                <div class="col-md-4">
                    <label class="form-label">Description</label>
                    <input type="text" class="form-control" name="item_description[]">
                </div>
                <div class="col-md-2">
                    <label class="form-label required-field">Quantity</label>
                    <input type="number" min="1" class="form-control item-quantity" name="item_quantity[]" 
                        value="1" required onchange="calculateTotal()">
                </div>
                <div class="col-md-2">
                    <label class="form-label required-field">Price</label>
                    <input type="number" step="0.01" min="0" class="form-control item-price" 
                        name="item_price[]" required onchange="calculateTotal()">
                </div>
                <div class="col-md-1">
                    <button type="button" class="btn btn-danger btn-sm delete-item-btn" onclick="removeItem(this)">
                        <i class="ri-delete-bin-line"></i>
                    </button>
                </div>
            `;
            itemsContainer.appendChild(newItem);
        }

        function removeItem(button) {
            const itemRow = button.closest('.item-row');
            if (document.querySelectorAll('.item-row').length > 1) {
                itemRow.remove();
                calculateTotal();
            } else {
                alert('You must have at least one item on the invoice.');
            }
        }

        function calculateTotal() {
            const quantities = document.querySelectorAll('.item-quantity');
            const prices = document.querySelectorAll('.item-price');
            let subtotal = 0;
            
            for (let i = 0; i < quantities.length; i++) {
                const quantity = parseFloat(quantities[i].value) || 0;
                const price = parseFloat(prices[i].value) || 0;
                subtotal += quantity * price;
            }
            
            const currency = document.getElementById('currency').value || ';
            document.getElementById('subtotal').textContent = `${currency} ${subtotal.toFixed(2)}`;
            document.getElementById('total').textContent = `${currency} ${subtotal.toFixed(2)}`;
        }

        // Initialize calculation on page load
        document.addEventListener('DOMContentLoaded', function() {
            calculateTotal();
        });
    </script>
</body>
</html>