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

$pdo = getDB();

// Handle GRN cancellation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['cancel_grn'])) {
    requirePermission('grn_manage');
    $grn_id = (int)$_POST['grn_id'];

    $stmt = $pdo->prepare("SELECT status FROM grns WHERE id = ?");
    $stmt->execute([$grn_id]);
    $grn = $stmt->fetch();

    if ($grn && $grn['status'] === 'Draft') {
        $pdo->prepare("UPDATE grns SET status = 'Cancelled' WHERE id = ?")->execute([$grn_id]);
        $_SESSION['success'] = 'GRN cancelled successfully.';
    } else {
        $_SESSION['error'] = 'Only Draft GRNs can be cancelled.';
    }
    header('Location: grn_list.php'); exit;
}

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

if (!empty($_GET['status'])) {
    $where .= ' AND g.status = ?';
    $params[] = $_GET['status'];
}
if (!empty($_GET['date_from'])) {
    $where .= ' AND DATE(g.received_date) >= ?';
    $params[] = $_GET['date_from'];
}
if (!empty($_GET['date_to'])) {
    $where .= ' AND DATE(g.received_date) <= ?';
    $params[] = $_GET['date_to'];
}

$stmt = $pdo->prepare("
    SELECT g.*, s.supplier_name, u.name as received_by_name
    FROM grns g
    LEFT JOIN suppliers s ON g.supplier_id = s.id
    LEFT JOIN users u ON g.received_by = u.id
    WHERE 1=1 $where
    ORDER BY g.created_at DESC
");
$stmt->execute($params);
$grns = $stmt->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-clipboard-list me-2"></i>Goods Received Notes (GRN)</h4>
            <a href="create_grn.php" class="btn btn-primary"><i class="fas fa-plus me-1"></i>Create GRN</a>
        </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="card">
            <div class="card-body">
                <form method="GET" class="row g-2 mb-3 no-print">
                    <div class="col-auto">
                        <select name="status" class="form-select form-select-sm">
                            <option value="">All Statuses</option>
                            <option value="Draft" <?= (($_GET['status'] ?? '') == 'Draft') ? 'selected' : '' ?>>Draft</option>
                            <option value="Received" <?= (($_GET['status'] ?? '') == 'Received') ? 'selected' : '' ?>>Received</option>
                            <option value="Cancelled" <?= (($_GET['status'] ?? '') == 'Cancelled') ? 'selected' : '' ?>>Cancelled</option>
                        </select>
                    </div>
                    <div class="col-auto">
                        <input type="date" name="date_from" class="form-control form-control-sm" value="<?= htmlspecialchars($_GET['date_from'] ?? '') ?>">
                    </div>
                    <div class="col-auto">
                        <input type="date" name="date_to" class="form-control form-control-sm" value="<?= htmlspecialchars($_GET['date_to'] ?? '') ?>">
                    </div>
                    <div class="col-auto">
                        <button type="submit" class="btn btn-sm btn-primary"><i class="fas fa-filter"></i> Filter</button>
                        <a href="grn_list.php" class="btn btn-sm btn-secondary"><i class="fas fa-times"></i> Reset</a>
                    </div>
                </form>

                <div class="table-responsive">
                    <table id="grnTable" class="table table-hover datatable">
                        <thead>
                            <tr><th>GRN No</th><th>Supplier</th><th>Date</th><th>Supplier Invoice</th><th>Total</th><th>Status</th><th>Received By</th><th>Actions</th></tr>
                        </thead>
                        <tbody>
                            <?php foreach ($grns as $g): ?>
                            <tr>
                                <td><strong><?= htmlspecialchars($g['grn_no']) ?></strong></td>
                                <td><?= htmlspecialchars($g['supplier_name'] ?? '-') ?></td>
                                <td><?= formatDate($g['received_date']) ?></td>
                                <td><?= htmlspecialchars($g['supplier_invoice_no'] ?? '-') ?></td>
                                <td><?= formatCurrency($g['total_amount']) ?></td>
                                <td>
                                    <?php if ($g['status'] == 'Draft'): ?>
                                    <span class="badge badge-waiting">Draft</span>
                                    <?php elseif ($g['status'] == 'Received'): ?>
                                    <span class="badge badge-completed">Received</span>
                                    <?php else: ?>
                                    <span class="badge badge-cancelled">Cancelled</span>
                                    <?php endif; ?>
                                </td>
                                <td><?= htmlspecialchars($g['received_by_name'] ?? '-') ?></td>
                                <td>
                                    <a href="view_grn.php?id=<?= $g['id'] ?>" class="btn btn-sm btn-info"><i class="fas fa-eye"></i></a>
                                    <a href="print_grn.php?id=<?= $g['id'] ?>" class="btn btn-sm btn-secondary" target="_blank"><i class="fas fa-print"></i></a>
                                    <?php if ($g['status'] === 'Draft'): ?>
                                    <form method="POST" style="display:inline" onsubmit="return confirm('Cancel this GRN?')">
                                        <input type="hidden" name="cancel_grn" value="1">
                                        <input type="hidden" name="grn_id" value="<?= $g['id'] ?>">
                                        <button type="submit" class="btn btn-sm btn-danger"><i class="fas fa-times"></i></button>
                                    </form>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
