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

$page_title = 'Lost Items';
$msg = '';

// Ensure claim_info table exists
$conn->query("CREATE TABLE IF NOT EXISTS claim_info (
    id INT AUTO_INCREMENT PRIMARY KEY,
    item_type ENUM('lost','found') NOT NULL,
    item_id INT NOT NULL,
    claimant_name VARCHAR(150) NOT NULL,
    claimant_contact VARCHAR(30) NOT NULL,
    remarks TEXT DEFAULT NULL,
    claimed_at DATETIME NOT NULL,
    released_by VARCHAR(150) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE KEY unique_claim (item_type, item_id)
)");

// Handle upload lost item
if (isset($_POST['upload_lost_item'])) {
    $item_name = sanitize($conn, $_POST['item_name']);
    $description = sanitize($conn, $_POST['description']);
    $category = sanitize($conn, $_POST['category']);
    $location = sanitize($conn, $_POST['location']);
    $date_lost = sanitize($conn, $_POST['date_lost']);
    $contact_number = sanitize($conn, $_POST['contact_number']);
    $reporter_name = sanitize($conn, $_POST['reporter_name']);
    $image_path = '';

    if (!empty($_FILES['image']['name'])) {
        $uploaded = uploadImage($_FILES['image']);
        if ($uploaded) $image_path = $uploaded;
        else { $msg = '<div class="alert alert-danger">Invalid image. Only JPG, JPEG, PNG allowed (max 5MB).</div>'; }
    }

    if (!$msg) {
        // Create a temporary user or use admin to associate the report
        // For now, we'll create a record with admin user_id and note the original reporter
        $conn->query("INSERT INTO lost_items (user_id, item_name, description, category, location, date_lost, image_path, contact_number) VALUES (" . $_SESSION['user_id'] . ",'$item_name','$description','$category','$location','$date_lost','$image_path','$contact_number')");
        $new_id = $conn->insert_id;
        // Run matching
        runMatchingAlgorithm($conn, $new_id);
        logActivity($conn, 'upload_lost_item', 'lost_item', $new_id, 'Admin uploaded lost item for: ' . $reporter_name);
        $msg = '<div class="alert alert-success">✓ Lost item uploaded successfully for ' . htmlspecialchars($reporter_name) . '! The system will now run matching.</div>';
    }
}

// Delete
if (isset($_POST['delete_item'])) {
    $id = (int)$_POST['item_id'];
    $item = $conn->query("SELECT image_path, item_name FROM lost_items WHERE id=$id")->fetch_assoc();
    if ($item && $item['image_path'] && file_exists('../' . $item['image_path'])) unlink('../' . $item['image_path']);
    $conn->query("DELETE FROM lost_items WHERE id=$id");
    logActivity($conn, 'delete_item', 'lost_item', $id, 'Deleted lost item: ' . $item['item_name']);
    $msg = '<div class="alert alert-success">Item deleted.</div>';
}

// Update status
if (isset($_POST['update_status'])) {
    $id = (int)$_POST['item_id'];
    $status = sanitize($conn, $_POST['status']);
    $item = $conn->query("SELECT item_name FROM lost_items WHERE id=$id")->fetch_assoc();

    if ($status === 'returned') {
        // Require claim info
        $claimant_name    = sanitize($conn, $_POST['claimant_name'] ?? '');
        $claimant_contact = sanitize($conn, $_POST['claimant_contact'] ?? '');
        $remarks          = sanitize($conn, $_POST['remarks'] ?? '');
        if (!$claimant_name || !$claimant_contact) {
            $msg = '<div class="alert alert-danger">Claimant name and contact number are required.</div>';
        } else {
            $admin_name  = sanitize($conn, $_SESSION['name'] ?? 'Admin');
            $claimed_at  = date('Y-m-d H:i:s');
            $conn->query("UPDATE lost_items SET status='returned' WHERE id=$id");
            $conn->query("INSERT INTO claim_info (item_type, item_id, claimant_name, claimant_contact, remarks, claimed_at, released_by)
                VALUES ('lost', $id, '$claimant_name', '$claimant_contact', '$remarks', '$claimed_at', '$admin_name')
                ON DUPLICATE KEY UPDATE
                    claimant_name='$claimant_name', claimant_contact='$claimant_contact',
                    remarks='$remarks', claimed_at='$claimed_at', released_by='$admin_name'");
            logActivity($conn, 'mark_returned', 'lost_item', $id, 'Marked as returned. Claimed by: ' . $claimant_name);
            $msg = '<div class="alert alert-success">Item marked as returned. Claim info saved.</div>';
        }
    } else {
        $conn->query("UPDATE lost_items SET status='$status' WHERE id=$id");
        logActivity($conn, 'update_status', 'lost_item', $id, 'Updated status to: ' . $status . ' for ' . $item['item_name']);
        $msg = '<div class="alert alert-success">Status updated.</div>';
    }
}

$search = sanitize($conn, $_GET['search'] ?? '');
$cat = sanitize($conn, $_GET['category'] ?? '');
$status_f = sanitize($conn, $_GET['status'] ?? '');
$where = "WHERE l.status != 'archived'";
if ($search) $where .= " AND (l.item_name LIKE '%$search%' OR l.description LIKE '%$search%' OR l.location LIKE '%$search%')";
if ($cat) $where .= " AND l.category='$cat'";
if ($status_f) $where .= " AND l.status='$status_f'";

$items = $conn->query("SELECT l.*, u.name as reporter, u.phone as user_phone,
    ci.claimant_name, ci.claimant_contact, ci.remarks as claim_remarks,
    ci.claimed_at, ci.released_by
    FROM lost_items l
    JOIN users u ON l.user_id=u.id
    LEFT JOIN claim_info ci ON ci.item_type='lost' AND ci.item_id=l.id
    $where ORDER BY l.created_at DESC");
$categories = $conn->query("SELECT name FROM categories ORDER BY name");
?>
<!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>
.img-preview { cursor: zoom-in; transition: transform .15s, box-shadow .15s; }
.img-preview:hover { transform: scale(1.08); box-shadow: 0 4px 12px rgba(0,0,0,.2); }
.zoom-overlay { display:none; position:fixed; inset:0; background:rgba(0,0,0,.88); 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; box-shadow:0 8px 40px rgba(0,0,0,.6); }
.zoom-close-btn { position:absolute; top:18px; right:22px; background:rgba(255,255,255,.15); border:none; color:#fff; font-size:26px; width:42px; height:42px; border-radius:50%; cursor:pointer; display:flex; align-items:center; justify-content:center; transition:background .2s; }
.zoom-close-btn:hover { background:rgba(255,255,255,.3); }
.zoom-caption { position:absolute; bottom:20px; left:50%; transform:translateX(-50%); color:rgba(255,255,255,.75); font-size:13px; font-weight:600; background:rgba(0,0,0,.4); padding:5px 16px; border-radius:20px; white-space:nowrap; max-width:80vw; overflow:hidden; text-overflow:ellipsis; }
.rf-form-header--lost { background:linear-gradient(135deg,#dcfce7,#bbf7d0); display:flex; align-items:center; gap:12px; padding:16px 20px; }
.rf-form-header--lost h2 { color:#15803d; margin:0; }
.rf-form-header--lost p { color:#7c2d12; font-size:13px; margin:2px 0 0 0; }
.rf-form-header-icon { font-size:28px; }
.rf-section-label { font-weight:700; color:var(--text); font-size:14px; margin-bottom:12px; margin-top:16px; }
.rf-required { color:#dc2626; font-weight:600; }
.rf-optional { color:#999; font-size:12px; font-weight:400; }
.rf-upload-zone { border:2px dashed #86efac; border-radius:8px; padding:28px 20px; text-align:center; cursor:pointer; background:var(--card-bg); transition:all .2s; user-select:none; }
.rf-upload-zone:hover { border-color:#22c55e; background:rgba(34,197,94,.04); }
.rf-upload-icon { font-size:40px; margin-bottom:8px; }
.rf-upload-text { font-weight:600; color:var(--text); margin-bottom:4px; }
.rf-upload-hint { font-size:12px; color:var(--text-muted); }
.rf-preview-wrap { display:flex; flex-direction:column; align-items:center; gap:10px; margin-top:12px; }
.rf-preview-img { max-width:100%; max-height:200px; border-radius:8px; border:1px solid var(--border); object-fit:cover; }
.rf-preview-remove { padding:6px 12px; background:#dc2626; color:white; border:none; border-radius:6px; cursor:pointer; font-weight:600; font-size:13px; transition:background .2s; }
.rf-preview-remove:hover { background:#b91c1c; }
.rf-notice { display:flex; align-items:center; gap:10px; padding:12px; background:rgba(34,197,94,.08); border-left:3px solid #22c55e; border-radius:4px; margin:16px 0; font-size:13px; color:var(--text); }
.rf-notice strong { color:#15803d; }
.rf-form-actions { display:flex; gap:12px; margin-top:20px; }
.rf-submit-btn { flex:1; }
.claim-detail-row { display:flex; gap:12px; align-items:center; padding:8px 12px; background:var(--bg-secondary); border-radius:6px; font-size:13px; color:var(--text); }
.claim-label { font-weight:700; color:var(--text-muted); min-width:110px; flex-shrink:0; }
.claim-modal-header { background:linear-gradient(135deg,#dcfce7,#bbf7d0); border-radius:var(--radius) var(--radius) 0 0; padding:16px 20px; }
body.dark-mode .claim-modal-header { background:linear-gradient(135deg,#052e16,#14532d); }
.claim-modal-header h3 { margin:0; color:#15803d; }
body.dark-mode .claim-modal-header h3 { color:#4ade80; }
.claim-modal-header small { color:#166534; }
body.dark-mode .claim-modal-header small { color:#86efac; }
</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="card">
                <div class="card-header">
                    <h3>🔍 Lost Items</h3>
                    <div style="display:flex;gap:8px">
                        <button onclick="openModal('uploadModal')" class="btn btn-success btn-sm">+ Upload Lost Item</button>
                        <a href="<?= BASE_URL ?>/admin/run_matching.php" class="btn btn-primary btn-sm">🤖 Run Matching</a>
                    </div>
                </div>
                <div class="card-body">
                    <!-- UPLOAD FORM MODAL -->
                    <div class="modal-overlay" id="uploadModal">
                        <div class="modal" style="max-width:640px;max-height:92vh;overflow-y:auto;padding:0">
                            <div class="modal-header" style="padding:0;border:none;margin-bottom:0">
                                <div class="rf-form-header rf-form-header--lost" style="width:100%;border-radius:var(--radius) var(--radius) 0 0;border-bottom:1px solid var(--border)">
                                    <div class="rf-form-header-icon">🔍</div>
                                    <div>
                                        <h2 style="font-size:17px">Upload Lost Item</h2>
                                        <p>For visitors without a phone or who reported items in person.</p>
                                    </div>
                                    <button class="modal-close" onclick="closeModal('uploadModal')" style="margin-left:auto">✕</button>
                                </div>
                            </div>

                            <form method="POST" enctype="multipart/form-data" style="padding:24px">
                                <input type="hidden" name="upload_lost_item" value="1">

                                <div class="rf-section-label">Item Details</div>

                                <div class="form-row">
                                    <div class="form-group">
                                        <label>Item Name <span class="rf-required">*</span></label>
                                        <input type="text" name="item_name" class="form-control" placeholder="e.g. Black Wallet, iPhone 12" required>
                                    </div>
                                    <div class="form-group">
                                        <label>Reporter Name <span class="rf-required">*</span></label>
                                        <input type="text" name="reporter_name" class="form-control" placeholder="Full name" required>
                                    </div>
                                </div>

                                <div class="form-row">
                                    <div class="form-group">
                                        <label>Category <span class="rf-required">*</span></label>
                                        <select name="category" class="form-control" required>
                                            <option value="">Select category</option>
                                            <?php $categories->data_seek(0); while($c=$categories->fetch_assoc()): ?>
                                            <option value="<?= $c['name'] ?>"><?= $c['name'] ?></option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label>Date Lost <span class="rf-required">*</span></label>
                                        <input type="date" name="date_lost" class="form-control" max="<?= date('Y-m-d') ?>" required>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label>Location Lost <span class="rf-required">*</span></label>
                                    <input type="text" name="location" class="form-control" placeholder="e.g. City Hall Lobby, 2nd Floor" required>
                                </div>

                                <div class="form-group">
                                    <label>Contact Number <span class="rf-required">*</span></label>
                                    <input type="text" name="contact_number" class="form-control" placeholder="09XXXXXXXXX" required>
                                </div>

                                <div class="form-group">
                                    <label>Description <span class="rf-optional">(optional but recommended)</span></label>
                                    <textarea name="description" class="form-control" rows="3" placeholder="Color, brand, size, distinguishing features..."></textarea>
                                </div>

                                <div class="rf-section-label" style="margin-top:4px">Photo</div>

                                <div class="form-group">
                                    <label>Item Photo <span class="rf-optional">(optional)</span></label>
                                    <div class="rf-upload-zone" id="adminUploadZone" onclick="document.getElementById('adminUploadImage').click()">
                                        <div class="rf-upload-icon">📷</div>
                                        <div class="rf-upload-text">Click to upload item photo</div>
                                        <div class="rf-upload-hint">JPG, JPEG, PNG &middot; Max 5MB</div>
                                    </div>
                                    <input type="file" id="adminUploadImage" name="image" accept=".jpg,.jpeg,.png" style="display:none"
                                           onchange="rfPreview(this,'adminUploadPreview','adminUploadZone')">
                                    <div id="adminUploadPreview" class="rf-preview-wrap" style="display:none">
                                        <img id="adminUploadPreviewImg" class="rf-preview-img">
                                        <button type="button" class="rf-preview-remove"
                                                onclick="rfRemove('adminUploadImage','adminUploadPreview','adminUploadZone')">✕ Remove</button>
                                    </div>
                                </div>

                                <div class="rf-notice">
                                    🤖 <strong>Auto-matching will run</strong> after submission — the system will automatically compare this item against all pending found item reports.
                                </div>

                                <div class="rf-form-actions">
                                    <button type="submit" class="btn btn-success btn-lg rf-submit-btn">📤 Submit Lost Item</button>
                                    <button type="button" class="btn btn-light" onclick="closeModal('uploadModal')">Cancel</button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- SEARCH FORM -->
                    <form method="GET" class="search-bar">
                        <input type="text" name="search" class="form-control" placeholder="Search items..." value="<?= htmlspecialchars($search) ?>">
                        <select name="category" class="form-control" style="max-width:160px">
                            <option value="">All Categories</option>
                            <?php $categories->data_seek(0); while($c=$categories->fetch_assoc()): ?>
                            <option value="<?= $c['name'] ?>" <?= $cat===$c['name']?'selected':'' ?>><?= $c['name'] ?></option>
                            <?php endwhile; ?>
                        </select>
                        <select name="status" class="form-control" style="max-width:140px">
                            <option value="">All Status</option>
                            <option value="pending" <?= $status_f==='pending'?'selected':'' ?>>Pending</option>
                            <option value="matched" <?= $status_f==='matched'?'selected':'' ?>>Matched</option>
                            <option value="returned" <?= $status_f==='returned'?'selected':'' ?>>Returned</option>
                        </select>
                        <button type="submit" class="btn btn-primary">Filter</button>
                        <a href="lost_items.php" class="btn btn-secondary">Clear</a>
                    </form>
                    <div class="table-wrapper">
                        <table>
                            <thead><tr><th>#</th><th>Image</th><th>Item Name</th><th>Category</th><th>Location</th><th>Date Lost</th><th>Reporter</th><th>Contact</th><th>Status</th><th>Actions</th></tr></thead>
                            <tbody>
                            <?php while($item = $items->fetch_assoc()): ?>
                            <tr>
                                <td><?= $item['id'] ?></td>
                                <td>
                                    <?php if($item['image_path']): ?>
                                    <img src="<?= BASE_URL ?>/<?= htmlspecialchars($item['image_path']) ?>" class="img-preview"
                                         onclick="zoomImage(this.src, '<?= htmlspecialchars(addslashes($item['item_name'])) ?>')"
                                         title="Click to zoom">
                                    <?php else: ?>
                                    <span style="font-size:24px">📷</span>
                                    <?php endif; ?>
                                </td>
                                <td><strong><?= htmlspecialchars($item['item_name']) ?></strong><br><small class="text-muted"><?= htmlspecialchars(substr($item['description'],0,50)) ?>...</small></td>
                                <td><?= htmlspecialchars($item['category']) ?></td>
                                <td><?= htmlspecialchars($item['location']) ?></td>
                                <td><?= $item['date_lost'] ? date('M d, Y', strtotime($item['date_lost'])) : '-' ?></td>
                                <td><?= htmlspecialchars($item['reporter']) ?></td>
                                <td><?= htmlspecialchars($item['contact_number'] ?: ($item['user_phone'] ?: '-')) ?></td>
                                <td>
                                    <span class="badge badge-<?= $item['status'] ?>"><?= $item['status'] ?></span>
                                    <?php if ($item['status'] === 'returned' && $item['claimant_name']): ?>
                                    <br><button onclick="openModal('claimView<?= $item['id'] ?>')" class="btn btn-xs" style="margin-top:4px;font-size:11px;padding:2px 7px;background:var(--success,#22c55e);color:#fff;border:none;border-radius:4px;cursor:pointer">📋 Claim Info</button>
                                    <!-- Claim Info View Modal -->
                                    <div class="modal-overlay" id="claimView<?= $item['id'] ?>">
                                        <div class="modal" style="max-width:440px">
                                            <div class="claim-modal-header">
                                                <div>
                                                    <h3 class="claim-modal-header-title">✅ Item Returned</h3>
                                                    <small class="claim-modal-header-sub"><?= htmlspecialchars($item['item_name']) ?></small>
                                                </div>
                                                <button class="modal-close" onclick="closeModal('claimView<?= $item['id'] ?>')">✕</button>
                                            </div>
                                            <div style="padding:20px;display:flex;flex-direction:column;gap:12px">
                                                <div class="claim-detail-row"><span class="claim-label">👤 Claimant</span><span><?= htmlspecialchars($item['claimant_name']) ?></span></div>
                                                <div class="claim-detail-row"><span class="claim-label">📞 Contact</span><span><?= htmlspecialchars($item['claimant_contact']) ?></span></div>
                                                <div class="claim-detail-row"><span class="claim-label">📅 Date & Time</span><span><?= date('M d, Y h:i A', strtotime($item['claimed_at'])) ?></span></div>
                                                <div class="claim-detail-row"><span class="claim-label">🏢 Released By</span><span><?= htmlspecialchars($item['released_by']) ?></span></div>
                                                <?php if($item['claim_remarks']): ?>
                                                <div class="claim-detail-row" style="align-items:flex-start"><span class="claim-label">📝 Remarks</span><span style="white-space:pre-wrap"><?= htmlspecialchars($item['claim_remarks']) ?></span></div>
                                                <?php endif; ?>
                                            </div>
                                            <div style="padding:0 20px 20px">
                                                <button onclick="closeModal('claimView<?= $item['id'] ?>')" class="btn btn-secondary btn-block">Close</button>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div style="display:flex;gap:4px;flex-wrap:wrap">
                                        <?php if ($item['status'] !== 'returned'): ?>
                                        <button onclick="openModal('statusModal<?= $item['id'] ?>')" class="btn btn-sm btn-warning">Status</button>
                                        <?php else: ?>
                                        <span style="font-size:11px;color:var(--text-muted);padding:4px 6px">Returned</span>
                                        <?php endif; ?>
                                        <form method="POST" action="archive.php"
                                              onsubmit="return confirm('Archive this item? It will be hidden from active lists.')">
                                            <input type="hidden" name="manual_archive" value="1">
                                            <input type="hidden" name="item_id" value="<?= $item['id'] ?>">
                                            <input type="hidden" name="item_type" value="lost">
                                            <button type="submit" class="btn btn-sm btn-secondary">🗄️ Archive</button>
                                        </form>
                                        <form method="POST" onsubmit="return confirmDelete(this)" data-item="<?= htmlspecialchars(addslashes($item['item_name'])) ?>">
                                            <input type="hidden" name="item_id" value="<?= $item['id'] ?>">
                                            <button type="submit" name="delete_item" class="btn btn-sm btn-danger">Delete</button>
                                        </form>
                                    </div>
                                    <!-- Status / Claim Modal -->
                                    <div class="modal-overlay" id="statusModal<?= $item['id'] ?>">
                                        <div class="modal" style="max-width:460px">
                                            <div class="modal-header">
                                                <h3>Update Status</h3>
                                                <button class="modal-close" onclick="closeModal('statusModal<?= $item['id'] ?>')">✕</button>
                                            </div>
                                            <form method="POST" id="statusForm<?= $item['id'] ?>">
                                                <input type="hidden" name="item_id" value="<?= $item['id'] ?>">
                                                <div class="form-group">
                                                    <label>Status</label>
                                                    <select name="status" class="form-control" onchange="toggleClaimFields(this, <?= $item['id'] ?>)">
                                                        <option value="pending" <?= $item['status']==='pending'?'selected':'' ?>>Pending</option>
                                                        <option value="matched" <?= $item['status']==='matched'?'selected':'' ?>>Matched</option>
                                                        <option value="returned" <?= $item['status']==='returned'?'selected':'' ?>>Returned</option>
                                                    </select>
                                                </div>
                                                <!-- Claim Fields -->
                                                <div id="claimFields<?= $item['id'] ?>" style="display:none">
                                                    <div style="background:linear-gradient(135deg,#dcfce7,#bbf7d0);border-radius:8px;padding:12px 14px;margin-bottom:14px;border-left:4px solid #16a34a">
                                                        <strong style="color:#15803d;font-size:13px">📋 Claim Information Required</strong>
                                                        <p style="margin:4px 0 0;font-size:12px;color:#166534">Please fill in the claimant's details before saving.</p>
                                                    </div>
                                                    <div class="form-group">
                                                        <label>Claimant's Full Name <span style="color:#dc2626">*</span></label>
                                                        <input type="text" name="claimant_name" class="form-control" placeholder="Enter full name">
                                                    </div>
                                                    <div class="form-group">
                                                        <label>Contact Number <span style="color:#dc2626">*</span></label>
                                                        <input type="text" name="claimant_contact" class="form-control" placeholder="09XXXXXXXXX">
                                                    </div>
                                                    <div class="form-group">
                                                        <label>Remarks <span style="color:#999;font-size:12px">(optional)</span></label>
                                                        <textarea name="remarks" class="form-control" rows="2" placeholder="e.g. Presented valid ID, described item accurately"></textarea>
                                                    </div>
                                                    <div style="background:#f0fdf4;border:1px solid #bbf7d0;border-radius:6px;padding:10px 12px;font-size:12px;color:#166534;margin-bottom:4px">
                                                        🕐 Date &amp; time will be recorded automatically.<br>
                                                        👤 Released by: <strong><?= htmlspecialchars($_SESSION['name'] ?? 'Admin') ?></strong>
                                                    </div>
                                                </div>
                                                <button type="submit" name="update_status" class="btn btn-primary btn-block" onclick="return validateClaim(<?= $item['id'] ?>)">Update</button>
                                            </form>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="<?= BASE_URL ?>/assets/js/main.js"></script>
<!-- Zoom Lightbox -->
<div class="zoom-overlay" id="zoomOverlay" onclick="closeZoom()">
    <button class="zoom-close-btn" onclick="closeZoom()">✕</button>
    <img id="zoomImg" src="" alt="">
    <div class="zoom-caption" id="zoomCaption"></div>
</div>
<script>
function zoomImage(src, caption) {
    document.getElementById('zoomImg').src = src;
    document.getElementById('zoomCaption').textContent = caption || '';
    document.getElementById('zoomOverlay').classList.add('open');
    document.body.style.overflow = 'hidden';
}
function closeZoom() {
    document.getElementById('zoomOverlay').classList.remove('open');
    document.getElementById('zoomImg').src = '';
    document.body.style.overflow = '';
}
function confirmDelete(form) {
    const itemName = form.dataset.item;
    return confirm('Are you sure you want to delete "' + itemName + '"?');
}
function openModal(modalId) {
    document.getElementById(modalId).style.display = 'flex';
    document.body.style.overflow = 'hidden';
}
function closeModal(modalId) {
    document.getElementById(modalId).style.display = 'none';
    document.body.style.overflow = '';
}

// Preview functions (matching found_items.php pattern)
function rfPreview(input, previewId, zoneId) {
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById(previewId + 'Img').src = e.target.result;
            document.getElementById(previewId).style.display = 'block';
        };
        reader.readAsDataURL(input.files[0]);
    }
}

function rfRemove(inputId, previewId, zoneId) {
    document.getElementById(inputId).value = '';
    document.getElementById(previewId).style.display = 'none';
}

// Upload Form Functions
function toggleUploadForm() {
    const form = document.getElementById('uploadFormContainer');
    if (form.style.display === 'none') {
        form.style.display = 'block';
    } else {
        form.style.display = 'none';
    }
}

function uploadPreview(input) {
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('uploadPreviewImg').src = e.target.result;
            document.getElementById('uploadPreview').style.display = 'block';
        };
        reader.readAsDataURL(input.files[0]);
    }
}

function removePreview() {
    document.getElementById('uploadImage').value = '';
    document.getElementById('uploadPreview').style.display = 'none';
}

document.addEventListener('keydown', e => { if(e.key==='Escape') closeZoom(); });

function toggleClaimFields(select, itemId) {
    const fields = document.getElementById('claimFields' + itemId);
    if (fields) fields.style.display = select.value === 'returned' ? 'block' : 'none';
}

function validateClaim(itemId) {
    const form = document.getElementById('statusForm' + itemId);
    const statusEl = form.querySelector('[name="status"]');
    if (statusEl && statusEl.value === 'returned') {
        const name = form.querySelector('[name="claimant_name"]').value.trim();
        const contact = form.querySelector('[name="claimant_contact"]').value.trim();
        if (!name || !contact) {
            alert('Please fill in the claimant\'s full name and contact number.');
            return false;
        }
    }
    return true;
}
</script>
</body>
</html>
