<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';
requirePermission('purchase_management');

$pdo = getDB();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'cancel_purchase') {
    $purchase_id = (int)$_POST['purchase_id'];
    try {
        $stmt = $pdo->prepare("SELECT * FROM purchases WHERE id = ? FOR UPDATE");
        $stmt->execute([$purchase_id]);
        $purchase = $stmt->fetch();
        if (!$purchase) { $_SESSION['error'] = 'Purchase not found.'; header('Location: purchases.php'); exit; }
        if ($purchase['purchase_status'] === 'Cancelled') { $_SESSION['error'] = 'Purchase is already cancelled.'; header('Location: purchases.php'); exit; }
        if ($purchase['purchase_status'] === 'Received') {
            $check = $pdo->prepare("SELECT COUNT(*) FROM product_imei pi JOIN purchase_items pii ON pi.purchase_item_id = pii.id WHERE pii.purchase_id = ? AND pi.status = 'Sold'");
            $check->execute([$purchase_id]);
            if ($check->fetchColumn() > 0) { $_SESSION['error'] = 'Cannot cancel: some items from this purchase have been sold.'; header('Location: purchases.php'); exit; }
        }
        $pdo->beginTransaction();
        if ($purchase['purchase_status'] === 'Received') {
            $items = $pdo->prepare("SELECT * FROM purchase_items WHERE purchase_id = ?");
            $items->execute([$purchase_id]);
            foreach ($items as $item) {
                createStockMovement($item['product_id'], 'adjustment', 'purchases', $purchase_id, 0, $item['quantity'], 'Purchase Cancelled', $_SESSION['user_id']);
            }
            $stmt = $pdo->prepare("UPDATE suppliers SET current_balance = current_balance - ? WHERE id = ?");
            $stmt->execute([$purchase['due_amount'], $purchase['supplier_id']]);
        }
        $stmt = $pdo->prepare("UPDATE purchases SET purchase_status = 'Cancelled' WHERE id = ?");
        $stmt->execute([$purchase_id]);
        $pdo->commit();
        logActivity('Cancelled Purchase', 'Purchases', $purchase_id, "Purchase #{$purchase['purchase_no']} cancelled");
        $_SESSION['success'] = "Purchase #{$purchase['purchase_no']} cancelled successfully.";
    } catch (Exception $e) {
        $pdo->rollBack();
        $_SESSION['error'] = 'Error cancelling purchase: ' . $e->getMessage();
    }
    header('Location: purchases.php'); exit;
}

$where = [];
$params = [];

if (!empty($_GET['date_from'])) { $where[] = "p.purchase_date >= ?"; $params[] = $_GET['date_from']; }
if (!empty($_GET['date_to'])) { $where[] = "p.purchase_date <= ?"; $params[] = $_GET['date_to']; }
if (!empty($_GET['supplier_id'])) { $where[] = "p.supplier_id = ?"; $params[] = (int)$_GET['supplier_id']; }
if (!empty($_GET['status'])) { $where[] = "p.purchase_status = ?"; $params[] = $_GET['status']; }

$where_clause = $where ? 'WHERE ' . implode(' AND ', $where) : '';

$purchases = $pdo->prepare("
    SELECT p.*, s.supplier_name, s.company_name, u.name as created_by_name
    FROM purchases p
    LEFT JOIN suppliers s ON p.supplier_id = s.id
    LEFT JOIN users u ON p.created_by = u.id
    $where_clause
    ORDER BY p.id DESC
");
$purchases->execute($params);
$purchases_list = $purchases->fetchAll();

$suppliers = $pdo->query("SELECT id, supplier_name, company_name FROM suppliers WHERE status = 1 ORDER BY supplier_name")->fetchAll();

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h4 class="page-title mb-0"><i class="fas fa-shopping-bag me-2"></i>Purchase Orders</h4>
            <div>
                <button class="btn btn-outline-secondary me-2" data-bs-toggle="collapse" data-bs-target="#filterSection"><i class="fas fa-filter me-1"></i>Filters</button>
                <a href="add_purchase.php" class="btn btn-primary"><i class="fas fa-plus me-1"></i>Add Purchase</a>
            </div>
        </div>
        <?php if (isset($_SESSION['success'])): ?><div class="alert alert-success alert-dismissible"><?= $_SESSION['success']; unset($_SESSION['success']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>
        <?php if (isset($_SESSION['error'])): ?><div class="alert alert-danger alert-dismissible"><?= $_SESSION['error']; unset($_SESSION['error']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

        <div class="collapse <?= (!empty($_GET['date_from']) || !empty($_GET['date_to']) || !empty($_GET['supplier_id']) || !empty($_GET['status'])) ? 'show' : '' ?>" id="filterSection">
            <div class="card mb-3">
                <div class="card-body">
                    <form method="GET" class="row g-3">
                        <div class="col-md-3">
                            <label class="form-label">Date From</label>
                            <input type="date" name="date_from" class="form-control" value="<?= htmlspecialchars($_GET['date_from'] ?? '') ?>">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Date To</label>
                            <input type="date" name="date_to" class="form-control" value="<?= htmlspecialchars($_GET['date_to'] ?? '') ?>">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Supplier</label>
                            <select name="supplier_id" class="form-select">
                                <option value="">All Suppliers</option>
                                <?php foreach ($suppliers as $s): ?>
                                <option value="<?= $s['id'] ?>" <?= (isset($_GET['supplier_id']) && $_GET['supplier_id'] == $s['id']) ? 'selected' : '' ?>><?= htmlspecialchars($s['supplier_name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Status</label>
                            <select name="status" class="form-select">
                                <option value="">All Status</option>
                                <option value="Pending" <?= (isset($_GET['status']) && $_GET['status'] === 'Pending') ? 'selected' : '' ?>>Pending</option>
                                <option value="Received" <?= (isset($_GET['status']) && $_GET['status'] === 'Received') ? 'selected' : '' ?>>Received</option>
                                <option value="Cancelled" <?= (isset($_GET['status']) && $_GET['status'] === 'Cancelled') ? 'selected' : '' ?>>Cancelled</option>
                            </select>
                        </div>
                        <div class="col-12">
                            <button type="submit" class="btn btn-primary"><i class="fas fa-search me-1"></i>Filter</button>
                            <a href="purchases.php" class="btn btn-outline-secondary">Clear</a>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table id="purchasesTable" class="table table-hover datatable">
                        <thead><tr><th>Purchase No</th><th>Supplier</th><th>Date</th><th>Total</th><th>Paid</th><th>Due</th><th>Status</th><th>Actions</th></tr></thead>
                        <tbody>
                            <?php if (!empty($purchases_list)): ?>
                            <?php foreach ($purchases_list as $pr): ?>
                            <tr>
                                <td><strong><?= htmlspecialchars($pr['purchase_no']) ?></strong></td>
                                <td><?= htmlspecialchars($pr['supplier_name'] ?? $pr['company_name'] ?? '-') ?></td>
                                <td><?= formatDate($pr['purchase_date']) ?></td>
                                <td><?= formatCurrency($pr['total_amount']) ?></td>
                                <td><?= formatCurrency($pr['paid_amount']) ?></td>
                                <td><span class="badge <?= $pr['due_amount'] > 0 ? 'badge-pending' : 'badge-completed' ?>"><?= formatCurrency($pr['due_amount']) ?></span></td>
                                <td><?= getStatusBadge($pr['purchase_status']) ?></td>
                                <td>
                                    <a href="view_purchase.php?id=<?= $pr['id'] ?>" class="btn btn-sm btn-outline-info" title="View"><i class="fas fa-eye"></i></a>
                                    <a href="print_purchase.php?id=<?= $pr['id'] ?>" class="btn btn-sm btn-outline-secondary" title="Print" target="_blank"><i class="fas fa-print"></i></a>
                                    <?php if ($pr['purchase_status'] !== 'Cancelled'): ?>
                                    <form method="POST" style="display:inline;" onsubmit="return confirm('Are you sure you want to cancel purchase #<?= htmlspecialchars($pr['purchase_no']) ?>? This action cannot be undone.');">
                                        <input type="hidden" name="action" value="cancel_purchase">
                                        <input type="hidden" name="purchase_id" value="<?= $pr['id'] ?>">
                                        <button type="submit" class="btn btn-sm btn-outline-danger" title="Cancel"><i class="fas fa-ban"></i></button>
                                    </form>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
