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

$page_title = 'Matches';
$msg = '';

// Approve match
if (isset($_POST['approve_match'])) {
    $id = (int)$_POST['match_id'];
    $match = $conn->query("SELECT * FROM matches WHERE id=$id")->fetch_assoc();
    if ($match) {
        $conn->query("UPDATE matches SET match_status='approved' WHERE id=$id");
        $conn->query("UPDATE lost_items SET status='matched' WHERE id={$match['lost_item_id']}");
        $conn->query("UPDATE found_items SET status='matched' WHERE id={$match['found_item_id']}");
        logActivity($conn, 'approve_match', 'match', $id, 'Approved match between lost item #' . $match['lost_item_id'] . ' and found item #' . $match['found_item_id']);
        // Get user IDs
            $lost = $conn->query("SELECT user_id, item_name, contact_number FROM lost_items WHERE id={$match['lost_item_id']}")->fetch_assoc();
        $found = $conn->query("SELECT user_id, item_name FROM found_items WHERE id={$match['found_item_id']}")->fetch_assoc();
        createNotification($conn, $lost['user_id'], "Great news! Your lost item '{$lost['item_name']}' has been matched and approved by admin. Please visit City Hall to claim it.", 'approved');
        createNotification($conn, $found['user_id'], "The found item '{$found['item_name']}' you reported has been matched with a lost item report.", 'approved');
        // SMS — send to registered phone and also to contact_number on the report
        $lost_user = $conn->query("SELECT phone FROM users WHERE id={$lost['user_id']}")->fetch_assoc();
        $found_user = $conn->query("SELECT phone FROM users WHERE id={$found['user_id']}")->fetch_assoc();
        $sms_lost = "RELINK: Your lost item '{$lost['item_name']}' has been matched! Visit Cauayan City Hall to claim it.";
        $sms_found = "RELINK: The found item '{$found['item_name']}' you reported has been matched with an owner.";
        if (!empty($lost_user['phone'])) sendSMS($conn, $lost_user['phone'], $sms_lost, $lost['user_id']);
        // Also send to contact_number on the report if different from registered phone
        if (!empty($lost['contact_number']) && $lost['contact_number'] !== $lost_user['phone'])
            sendSMS($conn, $lost['contact_number'], $sms_lost, $lost['user_id']);
        if (!empty($found_user['phone'])) sendSMS($conn, $found_user['phone'], $sms_found, $found['user_id']);
        $msg = '<div class="alert alert-success">Match approved! Users have been notified via system notification and SMS.</div>';
    }
}

// Reject match
if (isset($_POST['reject_match'])) {
    $id = (int)$_POST['match_id'];
    $match = $conn->query("SELECT * FROM matches WHERE id=$id")->fetch_assoc();
    $conn->query("UPDATE matches SET match_status='rejected' WHERE id=$id");
    logActivity($conn, 'reject_match', 'match', $id, 'Rejected match between lost item #' . $match['lost_item_id'] . ' and found item #' . $match['found_item_id']);
    $msg = '<div class="alert alert-info">Match rejected.</div>';
}

// Mark returned
if (isset($_POST['mark_returned'])) {
    $id = (int)$_POST['match_id'];
    $match = $conn->query("SELECT * FROM matches WHERE id=$id")->fetch_assoc();
    if ($match) {
        $conn->query("UPDATE matches SET match_status='returned' WHERE id=$id");
        $conn->query("UPDATE lost_items SET status='returned' WHERE id={$match['lost_item_id']}");
        $conn->query("UPDATE found_items SET status='returned' WHERE id={$match['found_item_id']}");
        logActivity($conn, 'mark_returned', 'match', $id, 'Marked match as returned for lost item #' . $match['lost_item_id']);
        $lost = $conn->query("SELECT user_id, item_name FROM lost_items WHERE id={$match['lost_item_id']}")->fetch_assoc();
        createNotification($conn, $lost['user_id'], "Your item '{$lost['item_name']}' has been marked as returned. Thank you for using RELINK!", 'approved');
        $msg = '<div class="alert alert-success">Item marked as returned.</div>';
    }
}

$status_f = sanitize($conn, $_GET['status'] ?? '');
$where = $status_f ? "WHERE m.match_status='$status_f'" : '';
$matches = $conn->query("
    SELECT m.*, 
        l.item_name as lost_name, l.category as lost_cat, l.location as lost_loc, l.image_path as lost_img,
        f.item_name as found_name, f.category as found_cat, f.location as found_loc, f.image_path as found_img, f.finder_photo as found_finder_photo,
        ul.name as lost_user, uf.name as found_user
    FROM matches m
    JOIN lost_items l ON m.lost_item_id = l.id
    JOIN found_items f ON m.found_item_id = f.id
    JOIN users ul ON l.user_id = ul.id
    JOIN users uf ON f.user_id = uf.id
    $where
    ORDER BY m.created_at 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="/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; }
</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 ?>
            <?php if(isset($_GET['msg']) && $_GET['msg']==='matching_done'): ?>
            <div class="alert alert-success">Matching algorithm ran successfully. New matches have been created if found.</div>
            <?php endif; ?>
            <div class="card mb-24">
                <div class="card-header">
                    <h3>🤝 Item Matches</h3>
                    <div style="display:flex;gap:8px">
                        <a href="?status=" class="btn btn-sm <?= !$status_f?'btn-primary':'btn-outline' ?>">All</a>
                        <a href="?status=pending" class="btn btn-sm <?= $status_f==='pending'?'btn-primary':'btn-outline' ?>">Pending</a>
                        <a href="?status=approved" class="btn btn-sm <?= $status_f==='approved'?'btn-primary':'btn-outline' ?>">Approved</a>
                        <a href="?status=rejected" class="btn btn-sm <?= $status_f==='rejected'?'btn-primary':'btn-outline' ?>">Rejected</a>
                    </div>
                </div>
                <div class="card-body">
                    <?php if($matches->num_rows === 0): ?>
                    <p class="text-center text-muted" style="padding:40px">No matches found.</p>
                    <?php endif; ?>
                    <?php while($m = $matches->fetch_assoc()): ?>
                    <div class="match-card">
                        <div class="match-item">
                            <div style="display:flex;gap:10px;align-items:center;margin-bottom:8px">
                                <?php if($m['lost_img']): ?><img src="/lostfound_relink/<?= htmlspecialchars($m['lost_img']) ?>" class="img-preview" title="Click to zoom" onclick="zoomImage(this.src,'<?= htmlspecialchars(addslashes($m['lost_name'])) ?> — Lost Item')"> <?php endif; ?>
                                <div>
                                    <h4>🔍 <?= htmlspecialchars($m['lost_name']) ?></h4>
                                    <p>📂 <?= htmlspecialchars($m['lost_cat']) ?> | 📍 <?= htmlspecialchars($m['lost_loc']) ?></p>
                                    <p>👤 <?= htmlspecialchars($m['lost_user']) ?></p>
                                </div>
                            </div>
                        </div>
                        <div class="match-score">
                            <div class="score"><?= $m['match_score'] ?>%</div>
                            <div class="label">Match Score</div>
                            <span class="badge badge-<?= $m['match_status'] ?>" style="margin-top:6px"><?= $m['match_status'] ?></span>
                            <?php if($m['match_status'] === 'pending'): ?>
                            <div style="display:flex;flex-direction:column;gap:4px;margin-top:8px">
                                <form method="POST"><input type="hidden" name="match_id" value="<?= $m['id'] ?>"><button name="approve_match" class="btn btn-sm btn-success">✅ Approve</button></form>
                                <form method="POST"><input type="hidden" name="match_id" value="<?= $m['id'] ?>"><button name="reject_match" class="btn btn-sm btn-danger">❌ Reject</button></form>
                            </div>
                            <?php elseif($m['match_status'] === 'approved'): ?>
                            <form method="POST" style="margin-top:8px"><input type="hidden" name="match_id" value="<?= $m['id'] ?>"><button name="mark_returned" class="btn btn-sm btn-primary">📬 Mark Returned</button></form>
                            <?php elseif($m['match_status'] === 'returned'): ?>
                            <div style="margin-top:8px;font-size:12px;color:var(--success);font-weight:700">✅ Item Returned</div>
                            <?php endif; ?>
                        </div>
                        <div class="match-item">
                            <div style="display:flex;gap:10px;align-items:center;margin-bottom:8px">
                                <?php if($m['found_img']): ?><img src="/lostfound_relink/<?= htmlspecialchars($m['found_img']) ?>" class="img-preview" title="Click to zoom" onclick="zoomImage(this.src,'<?= htmlspecialchars(addslashes($m['found_name'])) ?> — Found Item')"> <?php endif; ?>
                                <div>
                                    <h4>📦 <?= htmlspecialchars($m['found_name']) ?></h4>
                                    <p>📂 <?= htmlspecialchars($m['found_cat']) ?> | 📍 <?= htmlspecialchars($m['found_loc']) ?></p>
                                    <p>👤 <?= htmlspecialchars($m['found_user']) ?></p>
                                    <?php if(!empty($m['found_finder_photo'])): ?>
                                    <div style="margin-top:8px;display:flex;align-items:center;gap:8px">
                                        <img src="/lostfound_relink/<?= htmlspecialchars($m['found_finder_photo']) ?>" 
                                             style="width:40px;height:40px;border-radius:50%;object-fit:cover;border:2px solid var(--primary);cursor:zoom-in;transition:transform .15s"
                                             title="Click to zoom"
                                             onmouseover="this.style.transform='scale(1.1)'"
                                             onmouseout="this.style.transform='scale(1)'"
                                             onclick="zoomImage(this.src,'<?= htmlspecialchars(addslashes($m['found_user'])) ?> — Finder Photo')">
                                        <small style="color:var(--text-muted)">Finder's photo</small>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endwhile; ?>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="/lostfound_relink/assets/js/main.js"></script>
<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 = '';
}
document.addEventListener('keydown', e => { if(e.key === 'Escape') closeZoom(); });
</script>
</body>
</html>
