<?php
// admin/accounts/purchase-orders.php
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/functions.php';

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

// Handle Add PO
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_po'])) {
    $vendor_id = intval($_POST['vendor_id'] ?? 0);
    $order_date = $_POST['order_date'] ?? date('Y-m-d');
    $delivery_date = $_POST['delivery_date'] ?? null;
    $subtotal = floatval($_POST['subtotal'] ?? 0);
    $tax = floatval($_POST['tax'] ?? 0);
    $discount = floatval($_POST['discount'] ?? 0);
    $total = $subtotal + $tax - $discount;
    $note = sanitize($_POST['note'] ?? '');
    $items = $_POST['items'] ?? [];
    $paid_amount = 0;
    $due_amount = $total;
    
    if ($vendor_id <= 0 || $subtotal <= 0) {
        $error_msg = 'Vendor and subtotal are required';
    } else {
        $po_no = 'PO-' . date('Ymd') . '-' . rand(1000, 9999);
        
        try {
            $pdo->beginTransaction();
            
            $stmt = $pdo->prepare("INSERT INTO purchase_orders 
                (po_no, vendor_id, order_date, delivery_date, subtotal, tax, discount, total, paid_amount, due_amount, note, created_by) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([
                $po_no, $vendor_id, $order_date, $delivery_date, $subtotal, $tax, $discount, $total, $paid_amount, $due_amount, $note, $_SESSION['admin_id']
            ]);
            
            $po_id = $pdo->lastInsertId();
            
            // Insert PO items
            if (!empty($items)) {
                foreach ($items as $item) {
                    if (!empty($item['description']) && !empty($item['qty']) && !empty($item['price'])) {
                        $item_total = floatval($item['qty']) * floatval($item['price']);
                        $stmt = $pdo->prepare("INSERT INTO po_items 
                            (po_id, item_name, description, quantity, unit_price, total) 
                            VALUES (?, ?, ?, ?, ?, ?)");
                        $stmt->execute([
                            $po_id,
                            $item['description'],
                            $item['description'],
                            intval($item['qty']),
                            floatval($item['price']),
                            $item_total
                        ]);
                    }
                }
            }
            
            $pdo->commit();
            $_SESSION['success_msg'] = 'Purchase Order created successfully!';
            header('Location: purchase-orders.php');
            exit;
            
        } catch (Exception $e) {
            $pdo->rollBack();
            $error_msg = 'Error: ' . $e->getMessage();
        }
    }
}

// Handle Edit PO
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_po'])) {
    $po_id = intval($_POST['po_id'] ?? 0);
    $vendor_id = intval($_POST['vendor_id'] ?? 0);
    $order_date = $_POST['order_date'] ?? date('Y-m-d');
    $delivery_date = $_POST['delivery_date'] ?? null;
    $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'] ?? '');
    $items = $_POST['items'] ?? [];
    
    // Get current paid amount
    $stmt = $pdo->prepare("SELECT paid_amount FROM purchase_orders WHERE id = ?");
    $stmt->execute([$po_id]);
    $current = $stmt->fetch();
    $paid_amount = $current ? $current['paid_amount'] : 0;
    $due_amount = $total - $paid_amount;
    
    if ($po_id > 0 && $vendor_id > 0 && $subtotal > 0) {
        try {
            $pdo->beginTransaction();
            
            $stmt = $pdo->prepare("UPDATE purchase_orders SET 
                vendor_id = ?, order_date = ?, delivery_date = ?, 
                subtotal = ?, tax = ?, discount = ?, total = ?, 
                paid_amount = ?, due_amount = ?,
                status = ?, note = ? 
                WHERE id = ?");
            $stmt->execute([
                $vendor_id, $order_date, $delivery_date, 
                $subtotal, $tax, $discount, $total,
                $paid_amount, $due_amount,
                $status, $note, $po_id
            ]);
            
            // Delete existing items
            $stmt = $pdo->prepare("DELETE FROM po_items WHERE po_id = ?");
            $stmt->execute([$po_id]);
            
            // Insert updated items
            if (!empty($items)) {
                foreach ($items as $item) {
                    if (!empty($item['description']) && !empty($item['qty']) && !empty($item['price'])) {
                        $item_total = floatval($item['qty']) * floatval($item['price']);
                        $stmt = $pdo->prepare("INSERT INTO po_items 
                            (po_id, item_name, description, quantity, unit_price, total) 
                            VALUES (?, ?, ?, ?, ?, ?)");
                        $stmt->execute([
                            $po_id,
                            $item['description'],
                            $item['description'],
                            intval($item['qty']),
                            floatval($item['price']),
                            $item_total
                        ]);
                    }
                }
            }
            
            $pdo->commit();
            $_SESSION['success_msg'] = 'Purchase Order updated successfully!';
            header('Location: purchase-orders.php');
            exit;
            
        } catch (Exception $e) {
            $pdo->rollBack();
            $error_msg = 'Error: ' . $e->getMessage();
        }
    }
}

// Handle Delete via AJAX
if (isset($_POST['delete_po'])) {
    $delete_id = intval($_POST['delete_po']);
    try {
        $stmt = $pdo->prepare("DELETE FROM purchase_orders WHERE id = ?");
        $stmt->execute([$delete_id]);
        echo json_encode(['success' => true, 'message' => 'PO deleted']);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

// Get POs with calculated totals
$stmt = $pdo->query("SELECT po.*, v.name as vendor_name,
                     (SELECT COALESCE(SUM(amount), 0) FROM po_payments WHERE po_id = po.id) as total_paid
                     FROM purchase_orders po 
                     LEFT JOIN vendors v ON po.vendor_id = v.id 
                     ORDER BY po.created_at DESC");
$purchase_orders = $stmt->fetchAll();

// Update paid_amount and due_amount for each PO
foreach ($purchase_orders as &$po) {
    $po['paid_amount'] = $po['total_paid'] ?? 0;
    $po['due_amount'] = $po['total'] - $po['paid_amount'];
}
unset($po);

// Get vendors for dropdown
$vendors = $pdo->query("SELECT id, name FROM vendors WHERE status = 1 ORDER BY name")->fetchAll();

// Get single PO for view/edit
$view_po = null;
$view_items = [];
if (isset($_GET['view']) && intval($_GET['view']) > 0) {
    $view_id = intval($_GET['view']);
    $stmt = $pdo->prepare("SELECT po.*, v.name as vendor_name,
                           (SELECT COALESCE(SUM(amount), 0) FROM po_payments WHERE po_id = po.id) as total_paid
                           FROM purchase_orders po 
                           LEFT JOIN vendors v ON po.vendor_id = v.id 
                           WHERE po.id = ?");
    $stmt->execute([$view_id]);
    $view_po = $stmt->fetch();
    
    if ($view_po) {
        $view_po['paid_amount'] = $view_po['total_paid'] ?? 0;
        $view_po['due_amount'] = $view_po['total'] - $view_po['paid_amount'];
        
        $stmt = $pdo->prepare("SELECT * FROM po_items WHERE po_id = ?");
        $stmt->execute([$view_id]);
        $view_items = $stmt->fetchAll();
    }
}

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

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

.status-badge.draft { background: #e2e8f0; color: #64748b; }
.status-badge.pending { background: #fcd34d; color: #92400e; }
.status-badge.approved { background: #93c5fd; color: #1e40af; }
.status-badge.received { background: #86efac; color: #166534; }
.status-badge.partial { background: #f59e0b; color: #92400e; }
.status-badge.paid { background: #22c55e; color: #fff; }
.status-badge.cancelled { background: #fca5a5; color: #991b1b; }

.alert-container {
    margin-bottom: 20px;
}

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

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

.po-items-table th,
.po-items-table td {
    padding: 8px 12px;
    border-bottom: 1px solid #e2e8f0;
    text-align: left;
}

.po-items-table .text-right {
    text-align: right;
}

.po-summary {
    max-width: 350px;
    margin-left: auto;
}

.po-summary .summary-row {
    display: flex;
    justify-content: space-between;
    padding: 6px 0;
}

.po-summary .summary-row.total {
    font-weight: 700;
    border-top: 2px solid #0f172a;
    padding-top: 10px;
}

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

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

/* Modal Styles */
.modal-lg-custom {
    max-width: 900px;
}

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

.po-card .card-title {
    font-weight: 600;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #f1f5f9;
}

.po-stat {
    text-align: center;
    padding: 15px;
    background: #f8fafc;
    border-radius: 8px;
}

.po-stat .stat-number {
    font-size: 22px;
    font-weight: 700;
}

.po-stat .stat-label {
    font-size: 13px;
    color: #64748b;
}

@media (max-width: 768px) {
    .modal-lg-custom {
        max-width: 100%;
        margin: 10px;
    }
}
</style>

<div class="admin-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fa-solid fa-file-purchase me-2"></i> Purchase Orders</h2>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#poModal">
            <i class="fa-solid fa-plus"></i> Create PO
        </button>
    </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"><i class="fa-solid fa-file-invoice"></i> Invoices</a>
        <a href="purchase-orders.php" class="active"><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>
    
    <!-- Alert Container -->
    <div id="alertContainer" class="alert-container"></div>
    
    <?php if ($success_msg): ?>
    <div class="alert alert-success"><?php echo $success_msg; ?></div>
    <?php endif; ?>
    
    <?php if ($error_msg): ?>
    <div class="alert alert-danger"><?php echo $error_msg; ?></div>
    <?php endif; ?>
    
    <!-- Stats Cards -->
    <div class="row g-4 mb-4">
        <div class="col-lg-3 col-md-6">
            <div class="po-stat">
                <div class="stat-number text-primary"><?php echo count($purchase_orders); ?></div>
                <div class="stat-label">Total POs</div>
            </div>
        </div>
        <div class="col-lg-3 col-md-6">
            <div class="po-stat">
                <div class="stat-number text-success">
                    <?php 
                    $total_paid = 0;
                    foreach ($purchase_orders as $po) {
                        $total_paid += $po['paid_amount'];
                    }
                    echo number_format($total_paid);
                    ?> TK
                </div>
                <div class="stat-label">Total Paid</div>
            </div>
        </div>
        <div class="col-lg-3 col-md-6">
            <div class="po-stat">
                <div class="stat-number text-danger">
                    <?php 
                    $total_due = 0;
                    foreach ($purchase_orders as $po) {
                        $total_due += $po['due_amount'];
                    }
                    echo number_format($total_due);
                    ?> TK
                </div>
                <div class="stat-label">Total Due</div>
            </div>
        </div>
        <div class="col-lg-3 col-md-6">
            <div class="po-stat">
                <div class="stat-number text-warning">
                    <?php 
                    $total_amount = 0;
                    foreach ($purchase_orders as $po) {
                        $total_amount += $po['total'];
                    }
                    echo number_format($total_amount);
                    ?> TK
                </div>
                <div class="stat-label">Total Amount</div>
            </div>
        </div>
    </div>
    
    <!-- PO List -->
    <div class="card">
        <div class="card-body">
            <h5 class="card-title">Purchase Orders List</h5>
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>PO No</th>
                            <th>Vendor</th>
                            <th>Total</th>
                            <th>Paid</th>
                            <th>Due</th>
                            <th>Status</th>
                            <th>Date</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="poTableBody">
                        <?php if (empty($purchase_orders)): ?>
                        <tr>
                            <td colspan="8" class="text-center py-4">
                                <i class="fa-regular fa-file-purchase fa-2x text-muted d-block mb-2"></i>
                                No purchase orders found
                            </td>
                        </tr>
                        <?php else: ?>
                        <?php foreach ($purchase_orders as $po): ?>
                        <tr id="poRow_<?php echo $po['id']; ?>">
                            <td><code><?php echo $po['po_no']; ?></code></td>
                            <td><?php echo $po['vendor_name'] ?? 'N/A'; ?></td>
                            <td class="text-primary"><?php echo number_format($po['total']); ?> TK</td>
                            <td class="text-success"><?php echo number_format($po['paid_amount']); ?> TK</td>
                            <td class="text-danger"><?php echo number_format($po['due_amount']); ?> TK</td>
                            <td>
                                <span class="status-badge <?php echo $po['status']; ?>">
                                    <?php echo ucfirst($po['status']); ?>
                                </span>
                            </td>
                            <td><?php echo date('d M Y', strtotime($po['order_date'])); ?></td>
                            <td>
                                <button onclick="viewPO(<?php echo $po['id']; ?>)" class="btn btn-sm btn-primary">
                                    <i class="fa-solid fa-eye"></i>
                                </button>
                                <button onclick="editPO(<?php echo $po['id']; ?>)" class="btn btn-sm btn-warning">
                                    <i class="fa-solid fa-edit"></i>
                                </button>
                                <button onclick="deletePO(<?php echo $po['id']; ?>)" class="btn btn-sm btn-danger">
                                    <i class="fa-solid fa-trash"></i>
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- View PO Modal -->
<div class="modal fade" id="viewPOModal" tabindex="-1">
    <div class="modal-dialog modal-lg-custom">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fa-solid fa-file-purchase me-2"></i> Purchase Order Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="viewPOContent">
                <div class="text-center py-4">
                    <i class="fa-solid fa-spinner fa-spin fa-2x text-primary"></i>
                    <p class="mt-2">Loading...</p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add/Edit PO Modal -->
<div class="modal fade" id="poModal" tabindex="-1">
    <div class="modal-dialog modal-lg-custom">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="poModalTitle"><i class="fa-solid fa-plus-circle me-2"></i> Create Purchase Order</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" id="poForm">
                <input type="hidden" name="add_po" value="1" id="poFormAction">
                <input type="hidden" name="po_id" id="po_id" value="0">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Vendor <span class="text-danger">*</span></label>
                                <select name="vendor_id" id="po_vendor_id" class="form-control" required>
                                    <option value="">Select Vendor</option>
                                    <?php foreach ($vendors as $vendor): ?>
                                    <option value="<?php echo $vendor['id']; ?>"><?php echo htmlspecialchars($vendor['name']); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Order Date</label>
                                <input type="date" name="order_date" id="po_order_date" class="form-control" value="<?php echo date('Y-m-d'); ?>">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Delivery Date</label>
                                <input type="date" name="delivery_date" id="po_delivery_date" class="form-control">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Status</label>
                                <select name="status" id="po_status" class="form-control">
                                    <option value="draft">Draft</option>
                                    <option value="pending">Pending</option>
                                    <option value="approved">Approved</option>
                                    <option value="received">Received</option>
                                    <option value="partial">Partial</option>
                                    <option value="paid">Paid</option>
                                    <option value="cancelled">Cancelled</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Note</label>
                                <textarea name="note" id="po_note" class="form-control" rows="2"></textarea>
                            </div>
                        </div>
                    </div>
                    
                    <hr>
                    <h6 class="mb-3">PO Items</h6>
                    <div class="table-responsive">
                        <table class="po-items-table" id="poItemsTable">
                            <thead>
                                <tr>
                                    <th style="width:45%;">Item Description</th>
                                    <th style="width:20%;">Quantity</th>
                                    <th style="width:20%;">Unit Price</th>
                                    <th style="width:15%;">Total</th>
                                </tr>
                            </thead>
                            <tbody id="poItemsBody">
                                <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="addPOItem()">
                        <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="poDisplaySubtotal">0.00 TK</span>
                            </div>
                            <div class="mb-2 d-flex justify-content-between">
                                <strong>Tax:</strong>
                                <input type="number" name="tax" id="poTax" class="form-control form-control-sm" style="width:100px; display:inline-block;" value="0" step="0.01">
                            </div>
                            <div class="mb-2 d-flex justify-content-between">
                                <strong>Discount:</strong>
                                <input type="number" name="discount" id="poDiscount" class="form-control form-control-sm" style="width:100px; display:inline-block;" value="0" step="0.01">
                            </div>
                            <div class="mb-2 d-flex justify-content-between border-top pt-2">
                                <strong>Total:</strong>
                                <strong id="poDisplayTotal">0.00 TK</strong>
                            </div>
                            <input type="hidden" name="subtotal" id="poHiddenSubtotal" value="0">
                        </div>
                    </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">
                        <i class="fa-solid fa-save"></i> Save PO
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
var poItemCount = 1;
var currentViewPOId = 0;

// ========================================
// ADD PO ITEM
// ========================================
function addPOItem() {
    var html = `
        <tr>
            <td><input type="text" name="items[${poItemCount}][description]" class="form-control form-control-sm" placeholder="Item description"></td>
            <td><input type="number" name="items[${poItemCount}][qty]" class="form-control form-control-sm item-qty" value="1" min="1"></td>
            <td><input type="number" name="items[${poItemCount}][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('poItemsBody').insertAdjacentHTML('beforeend', html);
    poItemCount++;
}

// ========================================
// CALCULATE PO ITEM TOTAL
// ========================================
function calculatePOItemTotal(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);
    calculatePOTotal();
}

// ========================================
// CALCULATE PO TOTAL
// ========================================
function calculatePOTotal() {
    var totals = document.querySelectorAll('#poItemsBody .item-total');
    var subtotal = 0;
    totals.forEach(function(input) {
        subtotal += parseFloat(input.value) || 0;
    });
    
    var tax = parseFloat(document.getElementById('poTax').value) || 0;
    var discount = parseFloat(document.getElementById('poDiscount').value) || 0;
    var total = subtotal + tax - discount;
    
    document.getElementById('poDisplaySubtotal').textContent = subtotal.toFixed(2) + ' TK';
    document.getElementById('poDisplayTotal').textContent = total.toFixed(2) + ' TK';
    document.getElementById('poHiddenSubtotal').value = subtotal.toFixed(2);
}

// ========================================
// VIEW PO
// ========================================
function viewPO(id) {
    currentViewPOId = id;
    var modal = new bootstrap.Modal(document.getElementById('viewPOModal'));
    modal.show();
    
    // Load PO details
    fetch('get-po.php?id=' + id)
        .then(response => response.json())
        .then(data => {
            if (data.po) {
                var html = `
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <h6>PO Information</h6>
                            <p><strong>PO No:</strong> ${data.po.po_no}</p>
                            <p><strong>Vendor:</strong> ${data.po.vendor_name || 'N/A'}</p>
                            <p><strong>Order Date:</strong> ${data.po.order_date}</p>
                            <p><strong>Delivery Date:</strong> ${data.po.delivery_date || 'Not set'}</p>
                            <p><strong>Status:</strong> <span class="status-badge ${data.po.status}">${data.po.status}</span></p>
                        </div>
                        <div class="col-md-6">
                            <h6>Financial Summary</h6>
                            <p><strong>Subtotal:</strong> ${Number(data.po.subtotal).toFixed(2)} TK</p>
                            <p><strong>Tax:</strong> ${Number(data.po.tax).toFixed(2)} TK</p>
                            <p><strong>Discount:</strong> ${Number(data.po.discount).toFixed(2)} TK</p>
                            <p><strong>Total:</strong> ${Number(data.po.total).toFixed(2)} TK</p>
                            <p><strong>Paid:</strong> <span class="text-success">${Number(data.po.paid_amount).toFixed(2)} TK</span></p>
                            <p><strong>Due:</strong> <span class="text-danger">${Number(data.po.due_amount).toFixed(2)} TK</span></p>
                        </div>
                    </div>
                    
                    <h6>PO Items</h6>
                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <thead>
                                <tr>
                                    <th>Item</th>
                                    <th class="text-right">Qty</th>
                                    <th class="text-right">Unit Price</th>
                                    <th class="text-right">Total</th>
                                </tr>
                            </thead>
                            <tbody>
                    `;
                    
                    if (data.items && data.items.length > 0) {
                        data.items.forEach(function(item) {
                            html += `
                                <tr>
                                    <td>${item.item_name}</td>
                                    <td class="text-right">${item.quantity}</td>
                                    <td class="text-right">${Number(item.unit_price).toFixed(2)} TK</td>
                                    <td class="text-right">${Number(item.total).toFixed(2)} TK</td>
                                </tr>
                            `;
                        });
                    } else {
                        html += `<tr><td colspan="4" class="text-center">No items found</td></tr>`;
                    }
                    
                    html += `
                            </tbody>
                        </table>
                    </div>
                    
                    ${data.po.note ? `<div class="mt-3"><strong>Note:</strong> ${data.po.note}</div>` : ''}
                    
                    <div class="mt-3">
                        <button onclick="printPO(${data.po.id})" class="btn btn-print-po">
                            <i class="fa-solid fa-print"></i> Print PO
                        </button>
                        <button onclick="editPO(${data.po.id})" class="btn btn-warning">
                            <i class="fa-solid fa-edit"></i> Edit
                        </button>
                    </div>
                `;
                document.getElementById('viewPOContent').innerHTML = html;
            } else {
                document.getElementById('viewPOContent').innerHTML = `
                    <div class="alert alert-danger">PO not found</div>
                `;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('viewPOContent').innerHTML = `
                <div class="alert alert-danger">Failed to load PO details</div>
            `;
        });
}

// ========================================
// EDIT PO
// ========================================
function editPO(id) {
    fetch('get-po.php?id=' + id)
        .then(response => response.json())
        .then(data => {
            if (data.po) {
                document.getElementById('poModalTitle').innerHTML = '<i class="fa-solid fa-edit me-2"></i> Edit Purchase Order';
                document.getElementById('poFormAction').value = 'edit_po';
                document.getElementById('po_id').value = data.po.id;
                document.getElementById('po_vendor_id').value = data.po.vendor_id;
                document.getElementById('po_order_date').value = data.po.order_date;
                document.getElementById('po_delivery_date').value = data.po.delivery_date || '';
                document.getElementById('po_status').value = data.po.status;
                document.getElementById('po_note').value = data.po.note || '';
                document.getElementById('poTax').value = data.po.tax;
                document.getElementById('poDiscount').value = data.po.discount;
                
                // Clear existing items
                document.getElementById('poItemsBody').innerHTML = '';
                poItemCount = 0;
                
                // Add items
                if (data.items && data.items.length > 0) {
                    data.items.forEach(function(item, index) {
                        var html = `
                            <tr>
                                <td><input type="text" name="items[${index}][description]" class="form-control form-control-sm" value="${item.item_name}"></td>
                                <td><input type="number" name="items[${index}][qty]" class="form-control form-control-sm item-qty" value="${item.quantity}" min="1"></td>
                                <td><input type="number" name="items[${index}][price]" class="form-control form-control-sm item-price" step="0.01" value="${item.unit_price}"></td>
                                <td><input type="text" class="form-control form-control-sm item-total" value="${item.total}" readonly></td>
                            </tr>
                        `;
                        document.getElementById('poItemsBody').insertAdjacentHTML('beforeend', html);
                        poItemCount++;
                    });
                } else {
                    // Add default empty row
                    addPOItem();
                }
                
                calculatePOTotal();
                
                var modal = new bootstrap.Modal(document.getElementById('poModal'));
                modal.show();
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showAlert('danger', 'Failed to load PO data');
        });
}

// ========================================
// DELETE PO
// ========================================
function deletePO(id) {
    if (!confirm('Are you sure you want to delete this purchase order?')) return;
    
    var formData = new FormData();
    formData.append('delete_po', id);
    
    fetch('purchase-orders.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            var row = document.getElementById('poRow_' + id);
            if (row) {
                row.style.transition = 'all 0.5s ease';
                row.style.opacity = '0';
                setTimeout(function() {
                    row.remove();
                    var tbody = document.getElementById('poTableBody');
                    if (tbody.children.length === 0) {
                        tbody.innerHTML = `
                            <tr><td colspan="8" class="text-center py-4">
                                <i class="fa-regular fa-file-purchase fa-2x text-muted d-block mb-2"></i>
                                No purchase orders found
                            </td></tr>
                        `;
                    }
                }, 500);
            }
            showAlert('success', 'Purchase Order deleted successfully!');
        } else {
            showAlert('danger', data.message || 'Failed to delete PO');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('danger', 'Something went wrong');
    });
}

// ========================================
// PRINT PO
// ========================================
function printPO(id) {
    window.open('print-po.php?id=' + id, '_blank');
}

// ========================================
// SHOW ALERT
// ========================================
function showAlert(type, message) {
    var alertContainer = document.getElementById('alertContainer');
    var alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
    var icon = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle';
    
    alertContainer.innerHTML = `
        <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
            <i class="fa-solid ${icon} me-2"></i> ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    
    setTimeout(function() {
        var alert = alertContainer.querySelector('.alert');
        if (alert) {
            alert.style.transition = 'opacity 0.5s ease';
            alert.style.opacity = '0';
            setTimeout(function() { alert.remove(); }, 500);
        }
    }, 5000);
}

// ========================================
// EVENT LISTENERS
// ========================================
document.addEventListener('DOMContentLoaded', function() {
    // Item calculation events
    document.addEventListener('input', function(e) {
        if (e.target.classList.contains('item-qty') || e.target.classList.contains('item-price')) {
            calculatePOItemTotal(e.target);
        }
    });
    
    // Tax and discount events
    document.getElementById('poTax').addEventListener('input', calculatePOTotal);
    document.getElementById('poDiscount').addEventListener('input', calculatePOTotal);
    
    // Reset modal on close
    document.getElementById('poModal').addEventListener('hidden.bs.modal', function() {
        document.getElementById('poModalTitle').innerHTML = '<i class="fa-solid fa-plus-circle me-2"></i> Create Purchase Order';
        document.getElementById('poFormAction').value = 'add_po';
        document.getElementById('po_id').value = 0;
        document.getElementById('poForm').reset();
        document.getElementById('poItemsBody').innerHTML = '';
        poItemCount = 0;
        addPOItem();
        calculatePOTotal();
    });
});

// ========================================
// AUTO HIDE ALERTS
// ========================================
document.addEventListener('DOMContentLoaded', function() {
    var alerts = document.querySelectorAll('.alert');
    alerts.forEach(function(alert) {
        setTimeout(function() {
            if (alert) {
                alert.style.transition = 'opacity 0.5s ease';
                alert.style.opacity = '0';
                setTimeout(function() { alert.remove(); }, 500);
            }
        }, 5000);
    });
});
</script>

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