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

$pdo = getDB();
$user = currentUser();

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if (!$id) { $_SESSION['error'] = 'Invalid GRN ID.'; header('Location: grn_list.php'); exit; }

$stmt = $pdo->prepare("
    SELECT g.*, s.supplier_name, s.phone as supplier_phone, s.address as supplier_address,
           u.name as created_by_name, r.name as received_by_name
    FROM grns g
    LEFT JOIN suppliers s ON g.supplier_id = s.id
    LEFT JOIN users u ON g.created_by = u.id
    LEFT JOIN users r ON g.received_by = r.id
    WHERE g.id = ?
");
$stmt->execute([$id]);
$grn = $stmt->fetch();
if (!$grn) { $_SESSION['error'] = 'GRN not found.'; header('Location: grn_list.php'); exit; }

$stmt = $pdo->prepare("
    SELECT gi.*, p.product_name, p.product_type, p.product_code
    FROM grn_items gi
    JOIN products p ON gi.product_id = p.id
    WHERE gi.grn_id = ?
    ORDER BY gi.id
");
$stmt->execute([$id]);
$items = $stmt->fetchAll();

// Get IMEIs for each item
foreach ($items as &$item) {
    if ($item['product_type'] === 'phone') {
        $stmt = $pdo->prepare("SELECT imei_number, serial_number FROM grn_item_imeis WHERE grn_item_id = ?");
        $stmt->execute([$item['id']]);
        $item['imeis'] = $stmt->fetchAll();
    }
}
unset($item);

// Handle marking as Received (from Draft)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['receive_grn'])) {
    requirePermission('grn_manage');
    if ($grn['status'] !== 'Draft') {
        $_SESSION['error'] = 'Only Draft GRNs can be received.';
        header("Location: view_grn.php?id=$id"); exit;
    }

    try {
        $pdo->beginTransaction();

        foreach ($items as $item) {
            $stmt = $pdo->prepare("SELECT current_stock FROM products WHERE id = ? FOR UPDATE");
            $stmt->execute([$item['product_id']]);
            $current = (int)$stmt->fetchColumn();

            $pdo->prepare("UPDATE products SET current_stock = current_stock + ? WHERE id = ?")
                ->execute([$item['quantity'], $item['product_id']]);

            $new_balance = $current + $item['quantity'];
            $pdo->prepare("INSERT INTO stock_movements (product_id, movement_type, reference_type, reference_id, quantity_in, quantity_out, balance_after, note, created_by) VALUES (?, 'grn_receive', 'grn', ?, ?, 0, ?, ?, ?)")
                ->execute([$item['product_id'], $id, $item['quantity'], $new_balance, 'GRN received', $user['id']]);

            // Create IMEI records for phone products
            if ($item['product_type'] === 'phone' && !empty($item['imeis'])) {
                foreach ($item['imeis'] as $imei) {
                    $chk = $pdo->prepare("SELECT COUNT(*) FROM product_imei WHERE imei_number = ?");
                    $chk->execute([$imei['imei_number']]);
                    if ($chk->fetchColumn() == 0) {
                        $pdo->prepare("INSERT INTO product_imei (product_id, imei_number, purchase_item_id, status) VALUES (?,?,?, 'Available')")
                            ->execute([$item['product_id'], $imei['imei_number'], $item['id']]);
                    }
                }
            }
        }

        $pdo->prepare("UPDATE grns SET status = 'Received', received_by = ?, updated_at = NOW() WHERE id = ?")
            ->execute([$user['id'], $id]);

        $pdo->commit();
        $_SESSION['success'] = 'GRN received and stock updated.';
        header("Location: view_grn.php?id=$id"); exit;

    } catch (Exception $e) {
        $pdo->rollBack();
        $_SESSION['error'] = 'Error: ' . $e->getMessage();
    }
}

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>GRN Details - <?= htmlspecialchars($grn['grn_no']) ?></h4>
            <div class="no-print">
                <a href="print_grn.php?id=<?= $id ?>" class="btn btn-sm btn-secondary" target="_blank"><i class="fas fa-print"></i> Print</a>
                <?php if ($grn['status'] === 'Draft'): ?>
                <a href="create_grn.php?id=<?= $id ?>" class="btn btn-sm btn-info"><i class="fas fa-edit"></i> Edit</a>
                <form method="POST" style="display:inline" onsubmit="return confirm('Receive this GRN? Stock will be updated.')">
                    <input type="hidden" name="receive_grn" value="1">
                    <button type="submit" class="btn btn-sm btn-success"><i class="fas fa-check"></i> Mark Received</button>
                </form>
                <?php endif; ?>
                <a href="grn_list.php" class="btn btn-sm btn-secondary"><i class="fas fa-arrow-left"></i> Back</a>
            </div>
        </div>

        <?php if (isset($_SESSION['success'])): ?><div class="alert alert-success alert-dismissible"><?= $_SESSION['success']; unset($_SESSION['success']); ?></div><?php endif; ?>
        <?php if (isset($_SESSION['error'])): ?><div class="alert alert-danger alert-dismissible"><?= $_SESSION['error']; unset($_SESSION['error']); ?></div><?php endif; ?>

        <div class="row">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header"><i class="fas fa-info-circle me-2"></i>GRN Information</div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr><td width="140">GRN No:</td><td><strong><?= htmlspecialchars($grn['grn_no']) ?></strong></td></tr>
                            <tr><td>Status:</td><td>
                                <?php if ($grn['status'] == 'Draft'): ?>
                                <span class="badge badge-waiting">Draft</span>
                                <?php elseif ($grn['status'] == 'Received'): ?>
                                <span class="badge badge-completed">Received</span>
                                <?php else: ?>
                                <span class="badge badge-cancelled">Cancelled</span>
                                <?php endif; ?>
                            </td></tr>
                            <tr><td>Received Date:</td><td><?= formatDate($grn['received_date']) ?></td></tr>
                            <tr><td>Supplier Invoice:</td><td><?= htmlspecialchars($grn['supplier_invoice_no'] ?? '-') ?></td></tr>
                            <tr><td>PO No:</td><td><?= htmlspecialchars($grn['purchase_order_no'] ?? '-') ?></td></tr>
                            <tr><td>Received By:</td><td><?= htmlspecialchars($grn['received_by_name'] ?? '-') ?></td></tr>
                            <tr><td>Created By:</td><td><?= htmlspecialchars($grn['created_by_name'] ?? '-') ?></td></tr>
                            <?php if ($grn['note']): ?><tr><td>Note:</td><td><?= nl2br(htmlspecialchars($grn['note'])) ?></td></tr><?php endif; ?>
                        </table>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header"><i class="fas fa-truck me-2"></i>Supplier Information</div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr><td width="140">Name:</td><td><strong><?= htmlspecialchars($grn['supplier_name'] ?? '-') ?></strong></td></tr>
                            <tr><td>Phone:</td><td><?= htmlspecialchars($grn['supplier_phone'] ?? '-') ?></td></tr>
                            <tr><td>Address:</td><td><?= nl2br(htmlspecialchars($grn['supplier_address'] ?? '-')) ?></td></tr>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-header"><i class="fas fa-boxes me-2"></i>Items Received</div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-sm no-datatable">
                        <thead><tr><th>#</th><th>Product</th><th>Type</th><th>Qty</th><th>Cost Price</th><th>Selling Price</th><th>Total</th><th>IMEI</th></tr></thead>
                        <tbody>
                            <?php $i = 1; foreach ($items as $item): ?>
                            <tr>
                                <td><?= $i++ ?></td>
                                <td><?= htmlspecialchars($item['product_name']) ?><br><small class="text-muted"><?= htmlspecialchars($item['product_code']) ?></small></td>
                                <td><?= ucfirst($item['product_type']) ?></td>
                                <td><?= $item['quantity'] ?></td>
                                <td><?= formatCurrency($item['cost_price']) ?></td>
                                <td><?= formatCurrency($item['selling_price']) ?></td>
                                <td class="fw-bold"><?= formatCurrency($item['total_price']) ?></td>
                                <td>
                                    <?php if (!empty($item['imeis'])): ?>
                                    <?php foreach ($item['imeis'] as $imei): ?>
                                    <code><?= htmlspecialchars($imei['imei_number']) ?></code><br>
                                    <?php endforeach; ?>
                                    <?php elseif ($item['product_type'] === 'phone'): ?>
                                    <span class="text-muted">No IMEI</span>
                                    <?php else: ?>
                                    -
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-6 offset-md-6">
                <div class="card">
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr><td>Subtotal:</td><td class="text-end"><?= formatCurrency($grn['subtotal']) ?></td></tr>
                            <?php if ($grn['discount'] > 0): ?>
                            <tr><td>Discount:</td><td class="text-end">-<?= formatCurrency($grn['discount']) ?></td></tr>
                            <?php endif; ?>
                            <?php if ($grn['tax'] > 0): ?>
                            <tr><td>Tax:</td><td class="text-end"><?= formatCurrency($grn['tax']) ?></td></tr>
                            <?php endif; ?>
                            <tr class="fw-bold"><td>Total Amount:</td><td class="text-end"><?= formatCurrency($grn['total_amount']) ?></td></tr>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

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