<?php
require_once '../config/db.php';
require_once '../config/auth.php';
require_once '../config/functions.php';
requireAdmin();

// ── Ensure archived_items has all required columns ────────────────────────────
foreach ([
    'is_restored' => 'BOOLEAN DEFAULT FALSE',
    'restored_at' => 'TIMESTAMP NULL',
    'extra_data'  => 'JSON',
] as $_col => $_def) {
    $__r = $conn->query("SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='archived_items' AND COLUMN_NAME='$_col'");
    if ($__r && $__r->num_rows === 0)
        $conn->query("ALTER TABLE archived_items ADD COLUMN $_col $_def");
}
unset($_col, $_def, $__r);
// ─────────────────────────────────────────────────────────────────────────────

require_once '../config/archive_run.php';

$page_title = 'Archive';
$msg = '';
if (isset($_GET['success']) && $_GET['success'] === 'archived')
    $msg = '<div class="alert alert-success">✅ <strong>' . htmlspecialchars($_GET['name'] ?? 'Item') . '</strong> has been archived successfully.</div>';
if (isset($_GET['warning']) && $_GET['warning'] === 'already_archived')
    $msg = '<div class="alert alert-warning">⚠️ Item is already archived.</div>';

runAutoArchive($conn);

// Manual archive
if (isset($_POST['manual_archive'])) {
    $item_id   = (int)$_POST['item_id'];
    $item_type = $_POST['item_type'] === 'found' ? 'found' : 'lost';
    $table     = $item_type === 'lost' ? 'lost_items' : 'found_items';
    $item      = $conn->query("SELECT * FROM $table WHERE id=$item_id")->fetch_assoc();
    if ($item) {
        $conn->query("DELETE FROM archived_items WHERE source_item_id=$item_id AND source_type='$item_type' AND is_restored=TRUE");
        if (archiveItem($conn, $item_id, $item_type, $item)) {
            $conn->query("UPDATE $table SET status='archived' WHERE id=$item_id");
            $reason = $conn->real_escape_string('Manually Archived by Admin');
            $conn->query("UPDATE archived_items SET archive_reason='$reason' WHERE source_item_id=$item_id AND source_type='$item_type'");
            logActivity($conn, 'manual_archive', $table, $item_id, 'Manually archived ' . $item_type . ' item: ' . $item['item_name']);
            header('Location: archive.php?success=archived&name=' . urlencode($item['item_name']));
            exit;
        } else {
            header('Location: archive.php?warning=already_archived');
            exit;
        }
    }
}

// Restore
if (isset($_POST['restore_item'])) {
    $archive_id = (int)$_POST['archive_id'];
    $a = $conn->query("SELECT item_name, source_type FROM archived_items WHERE id=$archive_id")->fetch_assoc();
    if (restoreArchivedItem($conn, $archive_id)) {
        logActivity($conn, 'restore_archived', 'archived_item', $archive_id,
            'Restored archived ' . $a['source_type'] . ' item: ' . $a['item_name']);
        $msg = '<div class="alert alert-success">✅ Item restored to active ' . ucfirst($a['source_type']) . ' Items list.</div>';
    }
}

// Filters
$search = sanitize($conn, $_GET['search'] ?? '');
$type_f = sanitize($conn, $_GET['type']   ?? '');
$cat_f  = sanitize($conn, $_GET['category'] ?? '');
$year_f = sanitize($conn, $_GET['year']   ?? '');

$where = "WHERE is_restored = FALSE";
if ($search) $where .= " AND (item_name LIKE '%$search%' OR description LIKE '%$search%' OR location LIKE '%$search%' OR reporter_name LIKE '%$search%')";
if ($type_f) $where .= " AND source_type='$type_f'";
if ($cat_f)  $where .= " AND category='$cat_f'";
if ($year_f) $where .= " AND YEAR(archived_at)='$year_f'";

// CSV export
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    $rows = $conn->query("SELECT * FROM archived_items $where ORDER BY archived_at DESC");
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="archive_' . date('Ymd_His') . '.csv"');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['ID','Type','Item Name','Category','Location','Date Reported','Reporter','Contact','Original Status','Archive Reason','Archived At','Description']);
    while ($r = $rows->fetch_assoc()) {
        fputcsv($out, [
            $r['id'], $r['source_type'], $r['item_name'], $r['category'], $r['location'],
            $r['date_reported'], $r['reporter_name'], $r['contact_number'],
            $r['original_status'], $r['archive_reason'], $r['archived_at'], $r['description']
        ]);
    }
    fclose($out);
    exit;
}

$items      = $conn->query("SELECT a.* FROM archived_items a $where ORDER BY a.archived_at DESC");
$categories = $conn->query("SELECT name FROM categories ORDER BY name");
$total      = $conn->query("SELECT COUNT(*) c FROM archived_items $where")->fetch_assoc()['c'];
$total_all  = $conn->query("SELECT COUNT(*) c FROM archived_items WHERE is_restored = FALSE")->fetch_assoc()['c'];
$years_res  = $conn->query("SELECT DISTINCT YEAR(archived_at) y FROM archived_items WHERE is_restored = FALSE ORDER BY y DESC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= $page_title ?> - RELINK Admin</title>
<link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/style.css">
<style>
.badge-archived { background:#f3e8ff; color:#6b21a8; }
body.dark-mode .badge-archived { background:#2d1040; color:#d8b4fe; }
.archive-banner { background:linear-gradient(135deg,#f5f3ff,#ede9fe); border:1px solid #ddd6fe;
    border-radius:12px; padding:16px 20px; display:flex; align-items:center; gap:14px; margin-bottom:20px; }
body.dark-mode .archive-banner { background:linear-gradient(135deg,#1e1040,#2d1a5e); border-color:#4c1d95; }
.archive-banner-icon { font-size:32px; flex-shrink:0; }
.archive-banner-text h4 { color:#4c1d95; font-size:14px; font-weight:700; margin:0 0 3px; }
body.dark-mode .archive-banner-text h4 { color:#c4b5fd; }
.archive-banner-text p { color:#6b21a8; font-size:12px; margin:0; line-height:1.5; }
body.dark-mode .archive-banner-text p { color:#a78bfa; }
.archive-row td { vertical-align:middle; }
.archive-img { width:52px; height:52px; object-fit:cover; border-radius:8px; border:1px solid var(--border); cursor:zoom-in; }
.zoom-overlay { display:none; position:fixed; inset:0; background:rgba(0,0,0,.9); z-index:9999; align-items:center; justify-content:center; cursor:zoom-out; }
.zoom-overlay.open { display:flex; }
.zoom-overlay img { max-width:90vw; max-height:88vh; object-fit:contain; border-radius:10px; }
.zoom-close-btn { position:absolute; top:18px; right:22px; background:rgba(255,255,255,.15); border:none; color:#fff; font-size:22px; width:40px; height:40px; border-radius:50%; cursor:pointer; display:flex; align-items:center; justify-content:center; }
.detail-row-arch { display:flex; gap:10px; padding:9px 12px; background:var(--hover-bg,#f9fafb); border-radius:6px; font-size:13px; }
.detail-label-arch { font-weight:700; color:var(--text-muted); min-width:120px; flex-shrink:0; }
</style>
</head>
<body>
<div class="layout">
    <?php include '../includes/admin_sidebar.php'; ?>
    <div class="main-content">
        <?php include '../includes/topbar.php'; ?>
        <div class="page-content">
            <?= $msg ?>

            <div class="archive-banner">
                <div class="archive-banner-icon">🗄️</div>
                <div class="archive-banner-text">
                    <h4>Automatic Archiving System</h4>
                    <p>Items unclaimed for <strong>2 years</strong> from their posting date are automatically archived.
                       Archived items are hidden from the public Browse page and active item lists.
                       Total archived: <strong><?= $total_all ?></strong></p>
                </div>
                <a href="?<?= http_build_query(array_merge($_GET, ['export'=>'csv'])) ?>"
                   class="btn btn-sm btn-secondary" style="margin-left:auto;white-space:nowrap">
                    ⬇️ Export CSV
                </a>
            </div>

            <div class="card">
                <div class="card-header">
                    <h3>🗄️ Archived Items <span class="badge badge-archived"><?= $total ?></span></h3>
                </div>
                <div class="card-body">
                    <form method="GET" class="search-bar">
                        <input type="text" name="search" class="form-control" placeholder="Search name, location, reporter..."
                               value="<?= htmlspecialchars($search) ?>">
                        <select name="type" class="form-control" style="max-width:130px">
                            <option value="">All Types</option>
                            <option value="lost"  <?= $type_f==='lost' ?'selected':'' ?>>Lost</option>
                            <option value="found" <?= $type_f==='found'?'selected':'' ?>>Found</option>
                        </select>
                        <select name="category" class="form-control" style="max-width:160px">
                            <option value="">All Categories</option>
                            <?php while($c=$categories->fetch_assoc()): ?>
                            <option value="<?= htmlspecialchars($c['name']) ?>"
                                <?= $cat_f===$c['name']?'selected':'' ?>><?= htmlspecialchars($c['name']) ?></option>
                            <?php endwhile; ?>
                        </select>
                        <select name="year" class="form-control" style="max-width:110px">
                            <option value="">All Years</option>
                            <?php while($y=$years_res->fetch_assoc()): ?>
                            <option value="<?= $y['y'] ?>" <?= $year_f==$y['y']?'selected':'' ?>><?= $y['y'] ?></option>
                            <?php endwhile; ?>
                        </select>
                        <button type="submit" class="btn btn-primary">Filter</button>
                        <a href="archive.php" class="btn btn-secondary">Clear</a>
                    </form>

                    <?php if ($total === 0): ?>
                    <div style="text-align:center;padding:52px 20px;color:var(--text-muted)">
                        <div style="font-size:52px;margin-bottom:14px">🗄️</div>
                        <p style="font-size:15px;font-weight:600">No archived items found.</p>
                        <p style="font-size:13px">Items will appear here when they remain unclaimed for 2 years, or when manually archived by an admin.</p>
                    </div>
                    <?php else: ?>
                    <div class="table-wrapper">
                        <table>
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Image</th>
                                    <th>Item Name</th>
                                    <th>Type</th>
                                    <th>Category</th>
                                    <th>Location</th>
                                    <th>Reporter</th>
                                    <th>Contact</th>
                                    <th>Posted</th>
                                    <th>Archived</th>
                                    <th>Reason</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                            <?php $items->data_seek(0); while ($item = $items->fetch_assoc()): ?>
                            <tr class="archive-row">
                                <td><?= $item['id'] ?></td>
                                <td>
                                    <?php if ($item['image_path']): ?>
                                    <img src="<?= BASE_URL ?>/<?= htmlspecialchars($item['image_path']) ?>"
                                         class="archive-img"
                                         onclick="zoomImg('<?= BASE_URL ?>/<?= htmlspecialchars($item['image_path']) ?>')"
                                         title="Click to zoom">
                                    <?php else: ?>
                                    <span style="font-size:24px"><?= $item['source_type']==='lost'?'🔍':'📦' ?></span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <strong><?= htmlspecialchars($item['item_name']) ?></strong>
                                    <?php if ($item['description']): ?>
                                    <br><small class="text-muted"><?= htmlspecialchars(substr($item['description'],0,45)) ?>...</small>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="badge" style="background:<?= $item['source_type']==='lost'?'#fee2e2;color:#991b1b':'#dcfce7;color:#166534' ?>">
                                        <?= $item['source_type']==='lost'?'🔍 Lost':'📦 Found' ?>
                                    </span>
                                </td>
                                <td><?= htmlspecialchars($item['category'] ?: '—') ?></td>
                                <td><?= htmlspecialchars($item['location'] ?: '—') ?></td>
                                <td><?= htmlspecialchars($item['reporter_name'] ?: '—') ?></td>
                                <td><?= htmlspecialchars($item['contact_number'] ?: '—') ?></td>
                                <td><?= $item['date_reported'] ? date('M d, Y', strtotime($item['date_reported'])) : '—' ?></td>
                                <td style="white-space:nowrap">
                                    <?= date('M d, Y', strtotime($item['archived_at'])) ?><br>
                                    <small class="text-muted"><?= date('h:i A', strtotime($item['archived_at'])) ?></small>
                                </td>
                                <td>
                                    <span style="font-size:11px;color:#6b21a8;font-weight:600;background:#f5f3ff;padding:3px 8px;border-radius:20px;white-space:nowrap">
                                        ⏰ <?= htmlspecialchars($item['archive_reason']) ?>
                                    </span>
                                </td>
                                <td>
                                    <div style="display:flex;gap:4px;flex-wrap:wrap">
                                        <button onclick="openModal('viewModal<?= $item['id'] ?>')"
                                                class="btn btn-sm btn-info">View</button>
                                        <form method="POST" onsubmit="return confirm('Restore this item to the active list?')">
                                            <input type="hidden" name="archive_id" value="<?= $item['id'] ?>">
                                            <button type="submit" name="restore_item"
                                                    class="btn btn-sm btn-success">↩ Restore</button>
                                        </form>
                                    </div>

                                    <!-- View Detail Modal -->
                                    <div class="modal-overlay" id="viewModal<?= $item['id'] ?>">
                                        <div class="modal" style="max-width:520px;max-height:92vh;overflow-y:auto">
                                            <div class="modal-header"
                                                 style="background:linear-gradient(135deg,#f5f3ff,#ede9fe);border-radius:var(--radius) var(--radius) 0 0;padding:16px 20px;margin:-28px -28px 20px">
                                                <div>
                                                    <h3 style="margin:0;color:#4c1d95">🗄️ Archived Item Details</h3>
                                                    <small style="color:#6b21a8"><?= htmlspecialchars($item['item_name']) ?></small>
                                                </div>
                                                <button class="modal-close"
                                                        onclick="closeModal('viewModal<?= $item['id'] ?>')">✕</button>
                                            </div>

                                            <?php if ($item['image_path']): ?>
                                            <div style="text-align:center;margin-bottom:16px">
                                                <img src="<?= BASE_URL ?>/<?= htmlspecialchars($item['image_path']) ?>"
                                                     style="max-width:100%;max-height:200px;object-fit:contain;border-radius:10px;border:1px solid var(--border);cursor:zoom-in"
                                                     onclick="zoomImg('<?= BASE_URL ?>/<?= htmlspecialchars($item['image_path']) ?>')">
                                            </div>
                                            <?php endif; ?>

                                            <div style="display:flex;flex-direction:column;gap:8px">
                                                <div class="detail-row-arch">
                                                    <span class="detail-label-arch">📦 Item Name</span>
                                                    <span><?= htmlspecialchars($item['item_name']) ?></span>
                                                </div>
                                                <div class="detail-row-arch">
                                                    <span class="detail-label-arch">🏷️ Type</span>
                                                    <span><?= ucfirst($item['source_type']) ?> Item</span>
                                                </div>
                                                <div class="detail-row-arch">
                                                    <span class="detail-label-arch">📂 Category</span>
                                                    <span><?= htmlspecialchars($item['category'] ?: '—') ?></span>
                                                </div>
                                                <div class="detail-row-arch">
                                                    <span class="detail-label-arch">📍 Location</span>
                                                    <span><?= htmlspecialchars($item['location'] ?: '—') ?></span>
                                                </div>
                                                <div class="detail-row-arch">
                                                    <span class="detail-label-arch">📅 Date Reported</span>
                                                    <span><?= $item['date_reported'] ? date('M d, Y', strtotime($item['date_reported'])) : '—' ?></span>
                                                </div>
                                                <div class="detail-row-arch">
                                                    <span class="detail-label-arch">👤 Reporter</span>
                                                    <span><?= htmlspecialchars($item['reporter_name'] ?: '—') ?></span>
                                                </div>
                                                <div class="detail-row-arch">
                                                    <span class="detail-label-arch">📞 Contact</span>
                                                    <span><?= htmlspecialchars($item['contact_number'] ?: '—') ?></span>
                                                </div>
                                                <div class="detail-row-arch">
                                                    <span class="detail-label-arch">📋 Orig. Status</span>
                                                    <span class="badge badge-<?= $item['original_status'] ?>"><?= $item['original_status'] ?></span>
                                                </div>
                                                <?php if ($item['description']): ?>
                                                <div class="detail-row-arch" style="align-items:flex-start">
                                                    <span class="detail-label-arch">📝 Description</span>
                                                    <span style="white-space:pre-wrap"><?= htmlspecialchars($item['description']) ?></span>
                                                </div>
                                                <?php endif; ?>
                                                <div class="detail-row-arch" style="background:rgba(109,40,217,.06)">
                                                    <span class="detail-label-arch" style="color:#6b21a8">⏰ Archive Reason</span>
                                                    <span style="color:#6b21a8;font-weight:600"><?= htmlspecialchars($item['archive_reason']) ?></span>
                                                </div>
                                                <div class="detail-row-arch" style="background:rgba(109,40,217,.06)">
                                                    <span class="detail-label-arch" style="color:#6b21a8">🗓️ Archived On</span>
                                                    <span style="color:#6b21a8;font-weight:600"><?= date('M d, Y h:i A', strtotime($item['archived_at'])) ?></span>
                                                </div>
                                            </div>

                                            <div style="margin-top:20px;display:flex;gap:10px">
                                                <form method="POST" style="flex:1"
                                                      onsubmit="return confirm('Restore this item to the active list?')">
                                                    <input type="hidden" name="archive_id" value="<?= $item['id'] ?>">
                                                    <button type="submit" name="restore_item"
                                                            class="btn btn-success btn-block">↩ Restore Item</button>
                                                </form>
                                                <button onclick="closeModal('viewModal<?= $item['id'] ?>')"
                                                        class="btn btn-secondary">Close</button>
                                            </div>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="zoom-overlay" id="zoomOverlay" onclick="closeZoom()">
    <button class="zoom-close-btn" onclick="closeZoom()">✕</button>
    <img id="zoomImgEl" src="" alt="">
</div>

<script src="<?= BASE_URL ?>/assets/js/main.js"></script>
<script>
function openModal(id)  { document.getElementById(id).style.display='flex'; document.body.style.overflow='hidden'; }
function closeModal(id) { document.getElementById(id).style.display='none'; document.body.style.overflow=''; }
function zoomImg(src) {
    document.getElementById('zoomImgEl').src = src;
    document.getElementById('zoomOverlay').classList.add('open');
    document.body.style.overflow = 'hidden';
}
function closeZoom() {
    document.getElementById('zoomOverlay').classList.remove('open');
    document.getElementById('zoomImgEl').src = '';
    document.body.style.overflow = '';
}
document.addEventListener('keydown', e => { if(e.key==='Escape') closeZoom(); });
</script>
</body>
</html>
