<?php
// admin/accounts/invoices.php
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/functions.php';

if (!isAdmin()) {
    header('Location: ../login.php');
    exit;
}

// Handle Add Invoice
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_invoice'])) {
    $customer_name = sanitize($_POST['customer_name'] ?? '');
    $customer_email = sanitize($_POST['customer_email'] ?? '');
    $customer_phone = sanitize($_POST['customer_phone'] ?? '');
    $customer_address = sanitize($_POST['customer_address'] ?? '');
    $invoice_date = $_POST['invoice_date'] ?? date('Y-m-d');
    $due_date = $_POST['due_date'] ?? date('Y-m-d', strtotime('+30 days'));
    $subtotal = floatval($_POST['subtotal'] ?? 0);
    $tax = floatval($_POST['tax'] ?? 0);
    $discount = floatval($_POST['discount'] ?? 0);
    $total = $subtotal + $tax - $discount;
    $order_id = isset($_POST['order_id']) && !empty($_POST['order_id']) ? intval($_POST['order_id']) : null;
    $note = sanitize($_POST['note'] ?? '');
    $items = $_POST['items'] ?? [];
    
    if (empty($customer_name) || $subtotal <= 0) {
        $error_msg = 'Customer name and subtotal are required';
    } else {
        $invoice_no = 'INV-' . date('Ymd') . '-' . rand(1000, 9999);
        $stmt = $pdo->prepare("INSERT INTO invoices 
            (invoice_no, order_id, customer_name, customer_email, customer_phone, customer_address, 
             invoice_date, due_date, subtotal, tax, discount, total, note, created_by) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            $invoice_no, $order_id, $customer_name, $customer_email, $customer_phone, $customer_address,
            $invoice_date, $due_date, $subtotal, $tax, $discount, $total, $note, $_SESSION['admin_id']
        ]);
        $_SESSION['success_msg'] = 'Invoice created successfully!';
        header('Location: invoices.php');
        exit;
    }
}

// Get invoices
$stmt = $pdo->query("SELECT * FROM invoices ORDER BY created_at DESC");
$invoices = $stmt->fetchAll();

// Get totals
$stmt = $pdo->query("SELECT COALESCE(SUM(total), 0) as total FROM invoices");
$total_invoices = $stmt->fetch()['total'];

$stmt = $pdo->query("SELECT COALESCE(SUM(due_amount), 0) as total FROM invoices WHERE status NOT IN ('paid', 'cancelled')");
$total_due = $stmt->fetch()['total'];

$success_msg = $_SESSION['success_msg'] ?? '';
$error_msg = $_SESSION['error_msg'] ?? '';
unset($_SESSION['success_msg']);
unset($_SESSION['error_msg']);

include '../header.php';
?>

<style>
.account-nav {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-bottom: 20px;
    padding: 15px;
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.account-nav a {
    padding: 8px 20px;
    border-radius: 8px;
    color: #64748b;
    text-decoration: none;
    transition: all 0.3s ease;
}

.account-nav a:hover,
.account-nav a.active {
    background: #047dc3;
    color: #fff;
}

.stat-card {
    background: #fff;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    text-align: center;
}

.stat-card .stat-number {
    font-size: 28px;
    font-weight: 700;
}

.stat-card .stat-label {
    font-size: 14px;
    color: #64748b;
}

.status-badge {
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 500;
}

.status-badge.draft { background: #e2e8f0; color: #64748b; }
.status-badge.sent { background: #93c5fd; color: #1e40af; }
.status-badge.paid { background: #86efac; color: #166534; }
.status-badge.partial { background: #fcd34d; color: #92400e; }
.status-badge.overdue { background: #fca5a5; color: #991b1b; }
.status-badge.cancelled { background: #e2e8f0; color: #475569; }

/* Print Button */
.btn-print {
    background: #1e293b;
    color: #fff;
    border: none;
    padding: 8px 20px;
    border-radius: 8px;
    transition: all 0.3s ease;
}

.btn-print:hover {
    background: #0f172a;
    color: #fff;
}

/* Invoice Modal - Items Table */
.invoice-items-table {
    width: 100%;
    border-collapse: collapse;
}

.invoice-items-table th {
    background: #f1f5f9;
    padding: 8px 12px;
    text-align: left;
    font-weight: 600;
    font-size: 13px;
}

.invoice-items-table td {
    padding: 8px 12px;
    border-bottom: 1px solid #e2e8f0;
}

.invoice-items-table .item-total {
    font-weight: 600;
}
</style>

<div class="admin-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fa-solid fa-file-invoice me-2"></i> Invoices</h2>
        <div>
            <button class="btn btn-print me-2" onclick="window.location.href='invoice-list-print.php'">
                <i class="fa-solid fa-print"></i> Print All
            </button>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#invoiceModal">
                <i class="fa-solid fa-plus"></i> Create Invoice
            </button>
        </div>
    </div>
    
    <!-- Navigation -->
    <div class="account-nav">
        <a href="dashboard.php"><i class="fa-solid fa-chart-pie"></i> Dashboard</a>
        <a href="income.php"><i class="fa-solid fa-arrow-down"></i> Income</a>
        <a href="expenses.php"><i class="fa-solid fa-arrow-up"></i> Expenses</a>
        <a href="invoices.php" class="active"><i class="fa-solid fa-file-invoice"></i> Invoices</a>
        <a href="purchase-orders.php"><i class="fa-solid fa-file-purchase"></i> Purchase Orders</a>
        <a href="vendors.php"><i class="fa-solid fa-building"></i> Vendors</a>
        <a href="po-payments.php"><i class="fa-solid fa-hand-holding-dollar"></i> PO Payments</a>
        <a href="reports.php"><i class="fa-solid fa-chart-bar"></i> Reports</a>
    </div>
    
    <!-- Stats -->
    <div class="row g-4 mb-4">
        <div class="col-lg-4 col-md-6">
            <div class="stat-card">
                <div class="stat-number text-success"><?php echo number_format($total_invoices); ?> TK</div>
                <div class="stat-label">Total Invoices</div>
            </div>
        </div>
        <div class="col-lg-4 col-md-6">
            <div class="stat-card">
                <div class="stat-number text-danger"><?php echo number_format($total_due); ?> TK</div>
                <div class="stat-label">Total Due</div>
            </div>
        </div>
        <div class="col-lg-4 col-md-6">
            <div class="stat-card">
                <div class="stat-number"><?php echo count($invoices); ?></div>
                <div class="stat-label">Total Invoices</div>
            </div>
        </div>
    </div>
    
    <?php if ($success_msg): ?>
    <div class="alert alert-success"><?php echo $success_msg; ?></div>
    <?php endif; ?>
    
    <!-- Invoice List -->
    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>Invoice No</th>
                            <th>Customer</th>
                            <th>Total</th>
                            <th>Paid</th>
                            <th>Due</th>
                            <th>Status</th>
                            <th>Date</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="invoicesTableBody">
                        <?php if (empty($invoices)): ?>
                        <tr><td colspan="8" class="text-center">No invoices found</td></tr>
                        <?php else: ?>
                        <?php foreach ($invoices as $invoice): ?>
                        <tr id="invoiceRow_<?php echo $invoice['id']; ?>">
                            <td><code><?php echo $invoice['invoice_no']; ?></code></td>
                            <td><?php echo $invoice['customer_name']; ?></td>
                            <td><?php echo number_format($invoice['total']); ?> TK</td>
                            <td><?php echo number_format($invoice['paid_amount']); ?> TK</td>
                            <td class="text-danger"><?php echo number_format($invoice['due_amount']); ?> TK</td>
                            <td>
                                <span class="status-badge <?php echo $invoice['status']; ?>">
                                    <?php echo ucfirst($invoice['status']); ?>
                                </span>
                            </td>
                            <td><?php echo date('d M Y', strtotime($invoice['invoice_date'])); ?></td>
                            <td>
    <a href="view-invoice.php?id=<?php echo $invoice['id']; ?>" class="btn btn-sm btn-primary" title="View">
        <i class="fa-solid fa-eye"></i>
    </a>
    <a href="edit-invoice.php?id=<?php echo $invoice['id']; ?>" class="btn btn-sm btn-warning" title="Edit">
        <i class="fa-solid fa-edit"></i>
    </a>
    <a href="print-invoice.php?id=<?php echo $invoice['id']; ?>" class="btn btn-sm btn-success" title="Print" target="_blank">
        <i class="fa-solid fa-print"></i>
    </a>
    <button onclick="deleteInvoice(<?php echo $invoice['id']; ?>)" class="btn btn-sm btn-danger" title="Delete">
        <i class="fa-solid fa-trash"></i>
    </button>
</td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Create Invoice Modal -->
<div class="modal fade" id="invoiceModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fa-solid fa-plus-circle me-2"></i> Create Invoice</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="add_invoice" value="1">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Customer Name *</label>
                                <input type="text" name="customer_name" class="form-control" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Email</label>
                                <input type="email" name="customer_email" class="form-control">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Phone</label>
                                <input type="text" name="customer_phone" class="form-control">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Address</label>
                                <textarea name="customer_address" class="form-control" rows="2"></textarea>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Invoice Date</label>
                                <input type="date" name="invoice_date" class="form-control" value="<?php echo date('Y-m-d'); ?>">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Due Date</label>
                                <input type="date" name="due_date" class="form-control" value="<?php echo date('Y-m-d', strtotime('+30 days')); ?>">
                            </div>
                        </div>
                    </div>
                    <hr>
                    <h6 class="mb-3">Invoice Items</h6>
                    <div class="table-responsive">
                        <table class="invoice-items-table" id="itemsTable">
                            <thead>
                                <tr>
                                    <th style="width:40%;">Item Description</th>
                                    <th style="width:20%;">Quantity</th>
                                    <th style="width:20%;">Unit Price</th>
                                    <th style="width:20%;">Total</th>
                                </tr>
                            </thead>
                            <tbody id="itemsBody">
                                <tr>
                                    <td><input type="text" name="items[0][description]" class="form-control form-control-sm" placeholder="Item description"></td>
                                    <td><input type="number" name="items[0][qty]" class="form-control form-control-sm item-qty" value="1" min="1"></td>
                                    <td><input type="number" name="items[0][price]" class="form-control form-control-sm item-price" step="0.01" value="0"></td>
                                    <td><input type="text" class="form-control form-control-sm item-total" readonly></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <button type="button" class="btn btn-secondary btn-sm mt-2" onclick="addItemRow()">
                        <i class="fa-solid fa-plus"></i> Add Item
                    </button>
                    <hr>
                    <div class="row">
                        <div class="col-md-4 offset-md-8">
                            <div class="mb-2 d-flex justify-content-between">
                                <strong>Subtotal:</strong>
                                <span id="displaySubtotal">0.00 TK</span>
                            </div>
                            <div class="mb-2 d-flex justify-content-between">
                                <strong>Tax:</strong>
                                <input type="number" name="tax" id="taxInput" class="form-control form-control-sm" style="width:100px; display:inline-block;" value="0" step="0.01" onchange="calculateTotal()">
                            </div>
                            <div class="mb-2 d-flex justify-content-between">
                                <strong>Discount:</strong>
                                <input type="number" name="discount" id="discountInput" class="form-control form-control-sm" style="width:100px; display:inline-block;" value="0" step="0.01" onchange="calculateTotal()">
                            </div>
                            <div class="mb-2 d-flex justify-content-between border-top pt-2">
                                <strong>Total:</strong>
                                <strong id="displayTotal">0.00 TK</strong>
                            </div>
                            <input type="hidden" name="subtotal" id="hiddenSubtotal" value="0">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Note</label>
                        <textarea name="note" class="form-control" rows="2"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Create Invoice</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
var itemCount = 1;

function addItemRow() {
    var html = `
        <tr>
            <td><input type="text" name="items[${itemCount}][description]" class="form-control form-control-sm" placeholder="Item description"></td>
            <td><input type="number" name="items[${itemCount}][qty]" class="form-control form-control-sm item-qty" value="1" min="1" onchange="calculateItemTotal(this)"></td>
            <td><input type="number" name="items[${itemCount}][price]" class="form-control form-control-sm item-price" step="0.01" value="0" onchange="calculateItemTotal(this)"></td>
            <td><input type="text" class="form-control form-control-sm item-total" readonly></td>
        </tr>
    `;
    document.getElementById('itemsBody').insertAdjacentHTML('beforeend', html);
    itemCount++;
}

function calculateItemTotal(element) {
    var row = element.closest('tr');
    var qty = parseFloat(row.querySelector('.item-qty').value) || 0;
    var price = parseFloat(row.querySelector('.item-price').value) || 0;
    var total = qty * price;
    row.querySelector('.item-total').value = total.toFixed(2);
    calculateTotal();
}

function calculateTotal() {
    var totals = document.querySelectorAll('.item-total');
    var subtotal = 0;
    totals.forEach(function(input) {
        subtotal += parseFloat(input.value) || 0;
    });
    
    var tax = parseFloat(document.getElementById('taxInput').value) || 0;
    var discount = parseFloat(document.getElementById('discountInput').value) || 0;
    var total = subtotal + tax - discount;
    
    document.getElementById('displaySubtotal').textContent = subtotal.toFixed(2) + ' TK';
    document.getElementById('displayTotal').textContent = total.toFixed(2) + ' TK';
    document.getElementById('hiddenSubtotal').value = subtotal.toFixed(2);
}

// Initialize item calculations
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.item-qty, .item-price').forEach(function(input) {
        input.addEventListener('change', function() {
            calculateItemTotal(this);
        });
        input.addEventListener('keyup', function() {
            calculateItemTotal(this);
        });
    });
});

function deleteInvoice(id) {
    if (confirm('Delete this invoice?')) {
        fetch('delete-invoice.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'id=' + id
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) location.reload();
        });
    }
}

function viewInvoice(id) {
    window.open('view-invoice.php?id=' + id, '_blank');
}

function printInvoice(id) {
    window.open('print-invoice.php?id=' + id, '_blank');
}

function editInvoice(id) {
    alert('Edit functionality coming soon');
}
</script>

<?php include '../footer.php'; ?>