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

$page_title = 'Found 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)
)");

// Ensure surrendered_by and surrenderer_gender columns exist
$check_col = $conn->query("SHOW COLUMNS FROM found_items LIKE 'surrendered_by'");
if ($check_col->num_rows === 0) {
    $conn->query("ALTER TABLE found_items ADD COLUMN surrendered_by VARCHAR(150) DEFAULT NULL");
}
$check_gender = $conn->query("SHOW COLUMNS FROM found_items LIKE 'surrenderer_gender'");
if ($check_gender->num_rows === 0) {
    $conn->query("ALTER TABLE found_items ADD COLUMN surrenderer_gender ENUM('male','female') DEFAULT NULL");
}

// --- Admin Upload Found Item ---
if (isset($_POST['admin_upload'])) {
    $item_name   = sanitize($conn, $_POST['item_name']);
    $description = sanitize($conn, $_POST['description']);
    $category    = sanitize($conn, $_POST['category']);
    $location    = sanitize($conn, $_POST['location']);
    $date_found  = sanitize($conn, $_POST['date_found']);
    $surrendered = sanitize($conn, $_POST['surrendered_by']);
    $surrenderer_gender = in_array($_POST['surrenderer_gender'] ?? '', ['male','female']) ? $_POST['surrenderer_gender'] : null;
    $admin_id    = $_SESSION['user_id'];
    $image_path  = '';
    $finder_photo = '';

    if (!empty($_FILES['image']['name'])) {
        $uploaded = uploadImage($_FILES['image'], 'uploads/');
        if ($uploaded) $image_path = $uploaded;
    }

    if (!empty($_FILES['finder_photo']['name'])) {
        $uploaded = uploadImage($_FILES['finder_photo'], 'uploads/');
        if ($uploaded) $finder_photo = $uploaded;
    }

    $gender_val = $surrenderer_gender ? "'$surrenderer_gender'" : 'NULL';
    $conn->query("INSERT INTO found_items (user_id, item_name, description, category, location, date_found, image_path, finder_photo, surrendered_by, surrenderer_gender, status)
        VALUES ($admin_id, '$item_name', '$description', '$category', '$location', '$date_found', '$image_path', '$finder_photo', '$surrendered', $gender_val, 'pending')");
    $new_id = $conn->insert_id;
    logActivity($conn, 'admin_upload_found', 'found_item', $new_id, 'Admin uploaded surrendered item: ' . $item_name . ' from ' . $surrendered);
    runMatchingAlgorithm($conn, null, $new_id);
    $msg = '<div class="alert alert-success">✅ Found item recorded and matching triggered.</div>';
}

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

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

    if ($status === 'returned') {
        $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 found_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 ('found', $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', 'found_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 found_items SET status='$status' WHERE id=$id");
        logActivity($conn, 'update_status', 'found_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 f.status != 'archived'";
if ($search) $where .= " AND (f.item_name LIKE '%$search%' OR f.description LIKE '%$search%' OR f.location LIKE '%$search%')";
if ($cat) $where .= " AND f.category='$cat'";
if ($status_f) $where .= " AND f.status='$status_f'";

$items = $conn->query("SELECT f.*, u.name as reporter,
    ci.claimant_name, ci.claimant_contact, ci.remarks as claim_remarks,
    ci.claimed_at, ci.released_by
    FROM found_items f
    JOIN users u ON f.user_id=u.id
    LEFT JOIN claim_info ci ON ci.item_type='found' AND ci.item_id=f.id
    $where ORDER BY f.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="/lostfound_relink/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; }
.gender-card { display:flex; flex-direction:column; align-items:center; justify-content:center; gap:6px; width:100px; padding:14px 10px; border:2px solid var(--border); border-radius:12px; cursor:pointer; transition:border-color .2s, background .2s, transform .15s; background:var(--card-bg); user-select:none; }
.gender-card:hover { border-color:var(--primary); background:var(--hover-bg,rgba(99,102,241,.06)); transform:translateY(-2px); }
.gender-card.selected { border-color:var(--primary); background:rgba(99,102,241,.1); box-shadow:0 0 0 3px rgba(99,102,241,.15); }
.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>📦 Found Items</h3>
                    <button onclick="openModal('uploadModal')" class="btn btn-primary btn-sm">+ Upload Surrendered Item</button>
                </div>
                <div class="card-body">
                    <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 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="found_items.php" class="btn btn-secondary">Clear</a>
                    </form>
                        <div class="table-wrapper">
                        <table>
                            <thead><tr><th>#</th><th>Item Photo</th><th>Finder Photo</th><th>Item Name</th><th>Category</th><th>Location</th><th>Date Found</th><th>Reported By</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="/lostfound_relink/<?= htmlspecialchars($item['image_path']) ?>" class="img-preview" title="Click to zoom"
                                         onclick="zoomImage(this.src, '<?= htmlspecialchars(addslashes($item['item_name'])) ?> — Item Photo')">
                                    <?php else: ?><span style="font-size:24px">📷</span><?php endif; ?>
                                </td>
                                <td>
                                    <?php if(!empty($item['finder_photo'])): ?>
                                    <img src="/lostfound_relink/<?= htmlspecialchars($item['finder_photo']) ?>" class="img-preview" title="Click to zoom"
                                         style="border-radius:50%;border:2px solid var(--primary)"
                                         onclick="zoomImage(this.src, '<?= htmlspecialchars(addslashes($item['reporter'])) ?> — Finder Photo')">
                                    <?php else: ?><span style="font-size:22px;color:var(--text-muted)" title="No finder photo">👤</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_found'] ? date('M d, Y', strtotime($item['date_found'])) : '-' ?></td>
                                <td><?= htmlspecialchars($item['reporter']) ?>
                                    <?php if(!empty($item['surrendered_by'])): ?>
                                    <br><small style="color:var(--warning);font-weight:600">🏢 Walk-in: <?= htmlspecialchars($item['surrendered_by']) ?></small>
                                    <?php if(!empty($item['surrenderer_gender'])): ?>
                                    <br><small style="color:var(--text-muted)"><?= $item['surrenderer_gender']==='male'?'👨 Male':'👩 Female' ?></small>
                                    <?php endif; ?>
                                    <?php endif; ?>
                                </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>
                                    <div class="modal-overlay" id="claimView<?= $item['id'] ?>">
                                        <div class="modal" style="max-width:440px">
                                            <div class="claim-modal-header">
                                                <div>
                                                    <h3>✅ Item Returned</h3>
                                                    <small><?= 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 &amp; 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">
                                        <?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="found">
                                            <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>
                                    <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>
                                                <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="/lostfound_relink/assets/js/main.js"></script>
<!-- Upload Surrendered Item 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--found" 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 Surrendered Found Item</h2>
                    <p>For items physically surrendered to the office by walk-in individuals.</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="admin_upload" 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, Samsung Phone" required>
                </div>
                <div class="form-group">
                    <label>Surrendered By <span class="rf-required">*</span></label>
                    <input type="text" name="surrendered_by" class="form-control" placeholder="Full name of person" required>
                </div>
            </div>

            <div class="form-group">
                <label>Surrenderer's Gender <span class="rf-required">*</span></label>
                <div style="display:flex;gap:12px;margin-top:8px">
                    <label class="gender-card" id="gc-male">
                        <input type="radio" name="surrenderer_gender" value="male" required style="display:none" onchange="selectGender('male')">
                        <span style="font-size:32px">👨</span>
                        <span style="font-weight:600;font-size:14px">Male</span>
                    </label>
                    <label class="gender-card" id="gc-female">
                        <input type="radio" name="surrenderer_gender" value="female" style="display:none" onchange="selectGender('female')">
                        <span style="font-size:32px">👩</span>
                        <span style="font-weight:600;font-size:14px">Female</span>
                    </label>
                </div>
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label>Category</label>
                    <select name="category" class="form-control">
                        <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 Found</label>
                    <input type="date" name="date_found" class="form-control" value="<?= date('Y-m-d') ?>">
                </div>
            </div>

            <div class="form-group">
                <label>Location Found</label>
                <input type="text" name="location" class="form-control" placeholder="e.g. City Hall Lobby, 2nd Floor">
            </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, distinguishing features..."></textarea>
            </div>

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

            <div class="form-row">
                <div class="form-group">
                    <label>Item Photo <span class="rf-optional">(optional)</span></label>
                    <div class="rf-upload-zone" id="adminUploadZoneItem" onclick="document.getElementById('adminItemImg').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="adminItemImg" name="image" accept=".jpg,.jpeg,.png" style="display:none"
                           onchange="rfPreview(this,'adminItemPreview','adminUploadZoneItem')">
                    <div id="adminItemPreview" class="rf-preview-wrap" style="display:none">
                        <img id="adminItemPreviewImg" class="rf-preview-img">
                        <button type="button" class="rf-preview-remove"
                                onclick="rfRemove('adminItemImg','adminItemPreview','adminUploadZoneItem')">✕ Remove</button>
                    </div>
                </div>

                <div class="form-group">
                    <label>Surrenderer Photo <span class="rf-optional">(optional)</span></label>
                    <div class="rf-upload-zone" id="adminUploadZoneFinder" onclick="document.getElementById('adminFinderImg').click()">
                        <div class="rf-upload-icon">🤳</div>
                        <div class="rf-upload-text">Click to upload their photo</div>
                        <div class="rf-upload-hint">Helps verify identity &middot; Max 5MB</div>
                    </div>
                    <input type="file" id="adminFinderImg" name="finder_photo" accept=".jpg,.jpeg,.png" style="display:none"
                           onchange="rfPreview(this,'adminFinderPreview','adminUploadZoneFinder')">
                    <div id="adminFinderPreview" class="rf-preview-wrap" style="display:none">
                        <img id="adminFinderPreviewImg" class="rf-preview-img">
                        <button type="button" class="rf-preview-remove"
                                onclick="rfRemove('adminFinderImg','adminFinderPreview','adminUploadZoneFinder')">✕ Remove</button>
                    </div>
                </div>
            </div>

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

            <div class="rf-form-actions">
                <button type="submit" class="btn btn-primary btn-lg rf-submit-btn">📤 Submit Found Item</button>
                <button type="button" class="btn btn-light" onclick="closeModal('uploadModal')">Cancel</button>
            </div>
        </form>
    </div>
</div>
<!-- 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 selectGender(val) {
    document.getElementById('gc-male').classList.toggle('selected', val === 'male');
    document.getElementById('gc-female').classList.toggle('selected', val === 'female');
}
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 = '';
}
document.addEventListener('keydown', e => { if(e.key==='Escape') closeZoom(); });

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 confirmDelete(form) { return confirm('Delete "' + form.dataset.item + '"?'); }

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>
