<?php
// config.php ko shaamil karein, jo session aur database connection ko sambhalega.
require_once 'config.php';

// Yeh function jaanch karega ki user ke paas zaroori role hai ya nahi.
if (!function_exists('userHasRole')) {
    function userHasRole($required_roles) {
        if (!isset($_SESSION['user_roles'])) return false;
        if (!is_array($required_roles)) {
            $required_roles = [$required_roles];
        }
        return count(array_intersect($required_roles, $_SESSION['user_roles'])) > 0;
    }
}

// Suraksha jaanch: Ab Manager aur SMM bhi access kar sakte hain.
if (!userHasRole(['Admin', 'Manager', 'SMM', 'Sales'])) {
    // Agar permission nahi hai, to user ko dashboard par bhej dein.
    header('Location: dashboard.php');
    exit();
}

// --- FORM SUBMISSION LOGIC ---
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Form se data prapt karein
    $client_id = $_POST['client_id'];
    $client_name = $_POST['client_name'];
    $client_address = $_POST['client_address'];
    $invoice_date = $_POST['invoice_date'];
    $due_date = $_POST['due_date'];
    $status = 'Unpaid';
    $total_amount = 0;

    // Client ID validate karein
    if (empty($client_id) || !is_numeric($client_id)) {
        $_SESSION['message'] = "Invalid client selected. Please select a client from the list.";
        $_SESSION['message_type'] = 'error';
        header('Location: create-invoice.php');
        exit();
    } 
    
    $stmt_invoice = $conn->prepare("INSERT INTO invoices (client_id, client_name, client_address, invoice_date, due_date, total_amount, status) VALUES (?, ?, ?, ?, ?, ?, ?)");
    if ($stmt_invoice) {
        $stmt_invoice->bind_param("issssds", $client_id, $client_name, $client_address, $invoice_date, $due_date, $total_amount, $status);
        if ($stmt_invoice->execute()) {
            $invoice_id = $stmt_invoice->insert_id;
            $stmt_invoice->close();

            $stmt_item = $conn->prepare("INSERT INTO invoice_items (invoice_id, item_description, quantity, unit_price, total) VALUES (?, ?, ?, ?, ?)");
            if ($stmt_item) {
                $all_items_saved = true;
                if(isset($_POST['items'])) {
                    for ($i = 0; $i < count($_POST['items']['description']); $i++) {
                        $description = $_POST['items']['description'][$i];
                        $quantity = (float)$_POST['items']['quantity'][$i];
                        $price = (float)$_POST['items']['price'][$i];
                        $item_total = $quantity * $price;
                        $total_amount += $item_total;

                        if (!empty($description) && $quantity > 0) {
                            $stmt_item->bind_param("isddd", $invoice_id, $description, $quantity, $price, $item_total);
                            if (!$stmt_item->execute()) {
                                $all_items_saved = false;
                                $_SESSION['message'] = "Error saving invoice item: " . $stmt_item->error;
                                break;
                            }
                        }
                    }
                }
                $stmt_item->close();
                
                if ($all_items_saved) {
                    $update_stmt = $conn->prepare("UPDATE invoices SET total_amount = ? WHERE id = ?");
                    $update_stmt->bind_param("di", $total_amount, $invoice_id);
                    $update_stmt->execute();
                    $update_stmt->close();
                    header("Location: view-invoice.php?id=" . $invoice_id);
                    exit();
                } else {
                    $conn->query("DELETE FROM invoice_items WHERE invoice_id = $invoice_id");
                    $conn->query("DELETE FROM invoices WHERE id = $invoice_id");
                    $_SESSION['message_type'] = 'error';
                    header('Location: create-invoice.php');
                    exit();
                }
            } else {
                 $_SESSION['message'] = "Database Error: Could not prepare invoice items. Error: " . htmlspecialchars($conn->error);
                 $_SESSION['message_type'] = 'error';
                 $conn->query("DELETE FROM invoices WHERE id = $invoice_id");
                 header('Location: create-invoice.php');
                 exit();
            }
        } else {
            $_SESSION['message'] = "Error creating invoice: " . $stmt_invoice->error;
            $_SESSION['message_type'] = 'error';
            header('Location: create-invoice.php');
            exit();
        }
    } else {
        $_SESSION['message'] = "Database error: Could not prepare the invoice statement. " . $conn->error;
        $_SESSION['message_type'] = 'error';
        header('Location: create-invoice.php');
        exit();
    }
}

// --- PAGE DISPLAY LOGIC ---
$message = $_SESSION['message'] ?? '';
$message_type = $_SESSION['message_type'] ?? '';
unset($_SESSION['message'], $_SESSION['message_type']);

require_once 'header.php';

$clients_result = $conn->query("SELECT id, name FROM clients ORDER BY name ASC");
if (!$clients_result) {
    echo "<div class='p-6 text-red-600'>Database error: Could not fetch clients. " . $conn->error . "</div>";
    $clients = [];
} else {
    $clients = $clients_result->fetch_all(MYSQLI_ASSOC);
}
?>
<title>Create New Invoice - Digify OS</title>

<div class="p-6 md:p-10" x-data="invoiceForm()">
    <header class="flex justify-between items-center mb-6">
        <h2 class="text-2xl font-bold text-gray-800">Create New Invoice</h2>
        <a href="invoices.php" class="text-blue-600 hover:underline">&larr; Back to Invoices</a>
    </header>

    <?php if ($message): ?>
    <div class="mb-4 p-4 rounded-lg <?php echo ($message_type == 'error') ? 'bg-red-100 text-red-800' : 'bg-green-100 text-green-800'; ?>">
        <?php echo htmlspecialchars($message); ?>
    </div>
    <?php endif; ?>

    <form method="POST" action="create-invoice.php" class="bg-white p-8 rounded-lg shadow-md">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
            <!-- Client Details -->
            <div>
                <h3 class="text-lg font-semibold mb-4 text-gray-700 border-b pb-2">Bill To:</h3>
                <div class="space-y-4">
                     <div>
                        <label for="client_id" class="block text-sm font-medium text-gray-600">Select Client</label>
                        <select id="client_id" name="client_id" @change="populateClientDetails($event.target.value)" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500" required>
                            <option value="">-- Select a Client --</option>
                            <?php foreach ($clients as $client): ?>
                                <option value="<?php echo $client['id']; ?>"><?php echo htmlspecialchars($client['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label for="client_name" class="block text-sm font-medium text-gray-600">Client/Company Name</label>
                        <input type="text" id="client_name" name="client_name" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                    </div>
                    <div>
                        <label for="client_address" class="block text-sm font-medium text-gray-600">Address</label>
                        <textarea id="client_address" name="client_address" rows="3" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm"></textarea>
                    </div>
                </div>
            </div>
            <!-- Invoice Dates -->
            <div>
                 <h3 class="text-lg font-semibold mb-4 text-gray-700 border-b pb-2">Invoice Details:</h3>
                <div class="space-y-4">
                    <div>
                        <label for="invoice_date" class="block text-sm font-medium text-gray-600">Invoice Date</label>
                        <input type="date" id="invoice_date" name="invoice_date" value="<?php echo date('Y-m-d'); ?>" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                    </div>
                    <div>
                        <label for="due_date" class="block text-sm font-medium text-gray-600">Due Date</label>
                        <input type="date" id="due_date" name="due_date" value="<?php echo date('Y-m-d'); ?>" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                    </div>
                </div>
            </div>
        </div>

        <!-- Invoice Items -->
        <div class="mt-10">
            <h3 class="text-lg font-semibold text-gray-700 border-b pb-2 mb-4">Items</h3>
            <div class="space-y-4">
                <template x-for="(item, index) in items" :key="index">
                    <div class="grid grid-cols-12 gap-4 items-center">
                        <div class="col-span-5">
                            <input type="text" :name="'items[description]['+index+']'" x-model="item.description" placeholder="Item Description" class="w-full border-gray-300 rounded-md shadow-sm" required>
                        </div>
                        <div class="col-span-2">
                             <input type="number" :name="'items[quantity]['+index+']'" x-model.number="item.quantity" @input="calculateTotal()" placeholder="Qty" class="w-full border-gray-300 rounded-md shadow-sm" required>
                        </div>
                        <div class="col-span-2">
                            <input type="number" step="0.01" :name="'items[price]['+index+']'" x-model.number="item.price" @input="calculateTotal()" placeholder="Price" class="w-full border-gray-300 rounded-md shadow-sm">
                        </div>
                        <div class="col-span-2 text-right">
                            <span class="font-medium" x-text="formatCurrency(item.quantity * item.price)"></span>
                        </div>
                        <div class="col-span-1">
                            <button type="button" @click="removeItem(index)" class="text-red-500 hover:text-red-700">&times;</button>
                        </div>
                    </div>
                </template>
            </div>
            <button type="button" @click="addItem()" class="mt-4 px-4 py-2 bg-blue-500 text-white rounded-md text-sm">+ Add Item</button>
        </div>

        <!-- Totals -->
        <div class="mt-8 flex justify-end">
            <div class="w-full md:w-1/3">
                <div class="flex justify-between py-2">
                    <span class="font-semibold text-gray-600">Subtotal:</span>
                    <span class="font-semibold" x-text="formatCurrency(subtotal)"></span>
                </div>
                 <div class="flex justify-between py-2 border-t mt-2">
                    <span class="font-bold text-lg text-gray-800">Total:</span>
                    <span class="font-bold text-lg" x-text="formatCurrency(total)"></span>
                </div>
            </div>
        </div>

        <div class="mt-10 text-right">
            <button type="submit" class="px-8 py-3 bg-green-600 text-white font-semibold rounded-lg shadow-md hover:bg-green-700">Save Invoice</button>
        </div>
    </form>
</div>

<script>
function invoiceForm() {
    const clientsData = <?php echo json_encode($clients); ?>;
    const clientMap = {};
    clientsData.forEach(client => {
        clientMap[client.id] = { name: client.name };
    });

    return {
        items: [{ description: '', quantity: 1, price: 0 }],
        subtotal: 0,
        total: 0,
        init() { this.calculateTotal(); },
        addItem() { this.items.push({ description: '', quantity: 1, price: 0 }); },
        removeItem(index) {
            if (this.items.length > 1) this.items.splice(index, 1);
            this.calculateTotal();
        },
        calculateTotal() {
            let subtotal = 0;
            this.items.forEach(item => {
                const qty = parseFloat(item.quantity) || 0;
                const price = parseFloat(item.price) || 0;
                subtotal += qty * price;
            });
            this.subtotal = subtotal;
            this.total = this.subtotal;
        },
        formatCurrency(amount) {
            return new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' }).format(amount);
        },
        populateClientDetails(clientId) {
            const client = clientMap[clientId];
            document.getElementById('client_name').value = client ? client.name : '';
            document.getElementById('client_address').value = ''; 
        }
    }
}
</script>

<?php require_once 'footer.php'; ?>

