<?php
// admin/accounts/edit-invoice.php
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/functions.php';

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

$id = intval($_GET['id'] ?? 0);
if ($id <= 0) {
    $_SESSION['error_msg'] = 'Invalid Invoice ID';
    header('Location: invoices.php');
    exit;
}

// Get invoice details
$stmt = $pdo->prepare("SELECT * FROM invoices WHERE id = ?");
$stmt->execute([$id]);
$invoice = $stmt->fetch();

if (!$invoice) {
    $_SESSION['error_msg'] = 'Invoice not found';
    header('Location: invoices.php');
    exit;
}

$error_msg = '';
$success_msg = '';

// Handle Update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_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;
    $status = sanitize($_POST['status'] ?? 'draft');
    $note = sanitize($_POST['note'] ?? '');
    
    if (empty($customer_name) || $subtotal <= 0) {
        $error_msg = 'Customer name and subtotal are required';
    } else {
        $stmt = $pdo->prepare("UPDATE invoices SET 
            customer_name = ?, customer_email = ?, customer_phone = ?, customer_address = ?,
            invoice_date = ?, due_date = ?, subtotal = ?, tax = ?, discount = ?, 
            total = ?, status = ?, note = ? WHERE id = ?");
        $stmt->execute([
            $customer_name, $customer_email, $customer_phone, $customer_address,
            $invoice_date, $due_date, $subtotal, $tax, $discount,
            $total, $status, $note, $id
        ]);
        
        $_SESSION['success_msg'] = 'Invoice updated successfully!';
        header('Location: invoices.php');
        exit;
    }
}

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

<style>
.edit-invoice-wrapper {
    max-width: 1000px;
    margin: 0 auto;
}

.edit-invoice-card {
    background: #fff;
    border-radius: 12px;
    padding: 30px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.edit-invoice-card .card-title {
    font-size: 20px;
    font-weight: 600;
    padding-bottom: 15px;
    border-bottom: 2px solid #e2e8f0;
    margin-bottom: 25px;
}

.status-badge {
    padding: 4px 14px;
    border-radius: 20px;
    font-size: 13px;
    font-weight: 500;
    display: inline-block;
}

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

.invoice-items-table {
    width: 100%;
    border-collapse: collapse;
}

.invoice-items-table thead {
    background: #f1f5f9;
}

.invoice-items-table thead th {
    padding: 10px 12px;
    text-align: left;
    font-weight: 600;
    font-size: 13px;
    color: #475569;
}

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

.invoice-items-table .item-total {
    font-weight: 600;
}

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

<div class="admin-content">
    <div class="edit-invoice-wrapper">
        <div class="edit-invoice-card">
            <div class="d-flex justify-content-between align-items-center">
                <h5 class="card-title">
                    <i class="fa-solid fa-edit me-2"></i> Edit Invoice
                    <span class="status-badge <?php echo $invoice['status']; ?>"><?php echo ucfirst($invoice['status']); ?></span>
                </h5>
                <div>
                    <a href="print-invoice.php?id=<?php echo $invoice['id']; ?>" class="btn-print" target="_blank">
                        <i class="fa-solid fa-print"></i> Print
                    </a>
                    <a href="view-invoice.php?id=<?php echo $invoice['id']; ?>" class="btn btn-secondary ms-2">
                        <i class="fa-solid fa-eye"></i> View
                    </a>
                </div>
            </div>
            
            <?php if ($error_msg): ?>
            <div class="alert alert-danger"><?php echo $error_msg; ?></div>
            <?php endif; ?>
            
            <form method="POST">
                <input type="hidden" name="update_invoice" value="1">
                <input type="hidden" name="invoice_id" value="<?php echo $invoice['id']; ?>">
                
                <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" value="<?php echo htmlspecialchars($invoice['customer_name']); ?>" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Email</label>
                            <input type="email" name="customer_email" class="form-control" value="<?php echo htmlspecialchars($invoice['customer_email']); ?>">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Phone</label>
                            <input type="text" name="customer_phone" class="form-control" value="<?php echo htmlspecialchars($invoice['customer_phone']); ?>">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Address</label>
                            <textarea name="customer_address" class="form-control" rows="2"><?php echo htmlspecialchars($invoice['customer_address']); ?></textarea>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label class="form-label">Invoice Date</label>
                            <input type="date" name="invoice_date" class="form-control" value="<?php echo $invoice['invoice_date']; ?>">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Due Date</label>
                            <input type="date" name="due_date" class="form-control" value="<?php echo $invoice['due_date']; ?>">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Status</label>
                            <select name="status" class="form-control">
                                <option value="draft" <?php echo $invoice['status'] == 'draft' ? 'selected' : ''; ?>>Draft</option>
                                <option value="sent" <?php echo $invoice['status'] == 'sent' ? 'selected' : ''; ?>>Sent</option>
                                <option value="paid" <?php echo $invoice['status'] == 'paid' ? 'selected' : ''; ?>>Paid</option>
                                <option value="partial" <?php echo $invoice['status'] == 'partial' ? 'selected' : ''; ?>>Partial</option>
                                <option value="overdue" <?php echo $invoice['status'] == 'overdue' ? 'selected' : ''; ?>>Overdue</option>
                                <option value="cancelled" <?php echo $invoice['status'] == 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Invoice No</label>
                            <input type="text" class="form-control" value="<?php echo $invoice['invoice_no']; ?>" disabled>
                        </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:45%;">Item Description</th>
                                <th style="width:18%;">Quantity</th>
                                <th style="width:20%;">Unit Price</th>
                                <th style="width:17%;">Total</th>
                            </tr>
                        </thead>
                        <tbody id="itemsBody">
                            <?php 
                            // Sample items - replace with actual data
                            $items = [
                                ['description' => 'Premium Cotton Shirt', 'qty' => 2, 'price' => 1200, 'total' => 2400],
                                ['description' => 'Designer Saree', 'qty' => 1, 'price' => 2500, 'total' => 2500],
                            ];
                            $item_count = 0;
                            foreach ($items as $item): 
                            ?>
                            <tr>
                                <td><input type="text" name="items[<?php echo $item_count; ?>][description]" class="form-control form-control-sm" value="<?php echo $item['description']; ?>"></td>
                                <td><input type="number" name="items[<?php echo $item_count; ?>][qty]" class="form-control form-control-sm item-qty" value="<?php echo $item['qty']; ?>" min="1"></td>
                                <td><input type="number" name="items[<?php echo $item_count; ?>][price]" class="form-control form-control-sm item-price" step="0.01" value="<?php echo $item['price']; ?>"></td>
                                <td><input type="text" class="form-control form-control-sm item-total" value="<?php echo $item['total']; ?>" readonly></td>
                            </tr>
                            <?php 
                            $item_count++;
                            endforeach; 
                            ?>
                        </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"><?php echo number_format($invoice['subtotal']); ?> 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="<?php echo $invoice['tax']; ?>" step="0.01">
                        </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="<?php echo $invoice['discount']; ?>" step="0.01">
                        </div>
                        <div class="mb-2 d-flex justify-content-between border-top pt-2">
                            <strong>Total:</strong>
                            <strong id="displayTotal"><?php echo number_format($invoice['total']); ?> TK</strong>
                        </div>
                        <input type="hidden" name="subtotal" id="hiddenSubtotal" value="<?php echo $invoice['subtotal']; ?>">
                    </div>
                </div>
                
                <div class="mb-3">
                    <label class="form-label">Note</label>
                    <textarea name="note" class="form-control" rows="2"><?php echo htmlspecialchars($invoice['note']); ?></textarea>
                </div>
                
                <div class="mt-3">
                    <button type="submit" class="btn btn-primary">
                        <i class="fa-solid fa-save"></i> Update Invoice
                    </button>
                    <a href="invoices.php" class="btn btn-secondary">Cancel</a>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
var itemCount = <?php echo $item_count; ?>;

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"></td>
            <td><input type="number" name="items[${itemCount}][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>
    `;
    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 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);
        });
    });
    calculateTotal();
});
</script>

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