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

$page_title = 'My Reports';
$uid = $_SESSION['user_id'];
$tab = $_GET['tab'] ?? 'lost';
$msg = '';

if (isset($_POST['delete_lost'])) {
    $id = (int)$_POST['item_id'];
    $item = $conn->query("SELECT image_path FROM lost_items WHERE id=$id AND user_id=$uid")->fetch_assoc();
    if ($item) {
        if ($item['image_path'] && file_exists('../' . $item['image_path'])) unlink('../' . $item['image_path']);
        $conn->query("DELETE FROM lost_items WHERE id=$id AND user_id=$uid");
        $msg = '<div class="alert alert-success">Report deleted.</div>';
    }
}
if (isset($_POST['delete_found'])) {
    $id = (int)$_POST['item_id'];
    $item = $conn->query("SELECT image_path FROM found_items WHERE id=$id AND user_id=$uid")->fetch_assoc();
    if ($item) {
        if ($item['image_path'] && file_exists('../' . $item['image_path'])) unlink('../' . $item['image_path']);
        $conn->query("DELETE FROM found_items WHERE id=$id AND user_id=$uid");
        $msg = '<div class="alert alert-success">Report deleted.</div>';
    }
}

$lost_items  = $conn->query("SELECT * FROM lost_items WHERE user_id=$uid ORDER BY created_at DESC");
$found_items = $conn->query("SELECT * FROM found_items WHERE user_id=$uid ORDER BY created_at DESC");

// Status steps config
$lost_steps  = ['pending'=>0,'matched'=>1,'returned'=>2];
$found_steps = ['pending'=>0,'matched'=>1,'returned'=>2,'closed'=>3];

function statusStep($status, $steps) {
    return $steps[$status] ?? 0;
}
?>
<!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</title>
<link rel="stylesheet" href="/lostfound_relink/assets/css/style.css">
<style>
/* Timeline report cards */
.report-timeline { display:flex; flex-direction:column; gap:20px; }

.rt-card {
    background:var(--white); border:1px solid var(--border); border-radius:var(--radius);
    box-shadow:var(--shadow-sm); overflow:hidden; transition:var(--transition);
}
.rt-card:hover { box-shadow:var(--shadow-md); }

.rt-card-top {
    display:grid; grid-template-columns:100px 1fr; gap:0;
}
.rt-img {
    width:100px; height:100px; object-fit:cover; display:block; flex-shrink:0;
}
.rt-img-placeholder {
    width:100px; height:100px; background:var(--bg-secondary);
    display:flex; align-items:center; justify-content:center; font-size:36px; flex-shrink:0;
}
.rt-info { padding:14px 18px; flex:1; min-width:0; }
.rt-info-top { display:flex; align-items:flex-start; justify-content:space-between; gap:12px; flex-wrap:wrap; margin-bottom:8px; }
.rt-name { font-size:16px; font-weight:700; color:var(--text); }
.rt-meta { display:flex; flex-wrap:wrap; gap:12px; margin-bottom:10px; }
.rt-meta-item { font-size:12px; color:var(--text-muted); display:flex; align-items:center; gap:4px; }
.rt-desc { font-size:12px; color:var(--text-muted); line-height:1.5; }

/* Status progress bar */
.rt-progress {
    padding:14px 18px 16px;
    border-top:1px solid var(--border-light);
    background:var(--bg);
}
.rt-progress-label {
    font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:.8px;
    color:var(--text-muted); margin-bottom:10px;
}
.rt-steps {
    display:flex; align-items:center; gap:0;
}
.rt-step {
    display:flex; flex-direction:column; align-items:center; flex:1; position:relative;
}
.rt-step-dot {
    width:28px; height:28px; border-radius:50%; border:2px solid var(--border);
    background:var(--white); display:flex; align-items:center; justify-content:center;
    font-size:12px; font-weight:700; color:var(--text-muted); z-index:1;
    transition:all .3s ease;
}
.rt-step.done .rt-step-dot {
    background:var(--primary); border-color:var(--primary); color:#fff;
}
.rt-step.active .rt-step-dot {
    background:var(--white); border-color:var(--primary); color:var(--primary);
    box-shadow:0 0 0 3px rgba(79,157,28,.15);
}
.rt-step-label {
    font-size:10px; font-weight:600; color:var(--text-muted); margin-top:5px;
    text-align:center; white-space:nowrap;
}
.rt-step.done .rt-step-label,
.rt-step.active .rt-step-label { color:var(--primary); }

.rt-step-line {
    flex:1; height:2px; background:var(--border); margin-top:-14px; z-index:0;
    transition:background .3s ease;
}
.rt-step-line.done { background:var(--primary); }

/* returned special */
.rt-step.returned .rt-step-dot { background:#059669; border-color:#059669; color:#fff; }
.rt-step.returned .rt-step-label { color:#059669; }
.rt-step-line.returned { background:#059669; }

/* Actions row */
.rt-actions {
    padding:10px 18px; border-top:1px solid var(--border-light);
    display:flex; align-items:center; justify-content:space-between; gap:8px;
    background:var(--white);
}
.rt-date { font-size:11px; color:var(--text-muted); }

/* Empty state */
.rt-empty {
    text-align:center; padding:64px 24px; color:var(--text-muted);
    background:var(--bg-secondary); border-radius:var(--radius);
    border:1px dashed var(--border);
}
.rt-empty .icon { font-size:52px; margin-bottom:14px; opacity:.6; }

/* Dark mode */
body.dark-mode .rt-card { background:var(--white); border-color:var(--border); }
body.dark-mode .rt-progress { background:var(--bg); border-top-color:var(--border); }
body.dark-mode .rt-step-dot { background:var(--white); border-color:var(--border); }
body.dark-mode .rt-step.done .rt-step-dot { background:var(--primary); border-color:var(--primary); }
body.dark-mode .rt-actions { background:var(--white); border-top-color:var(--border); }
body.dark-mode .rt-name { color:var(--text); }
body.dark-mode .rt-img-placeholder { background:var(--bg-secondary); }

@media(max-width:600px){
    .rt-card-top { grid-template-columns:80px 1fr; }
    .rt-img, .rt-img-placeholder { width:80px; height:80px; }
    .rt-step-label { font-size:9px; }
}
</style>
</head>
<body>
<div class="layout">
    <?php include '../includes/user_sidebar.php'; ?>
    <div class="main-content">
        <?php include '../includes/topbar.php'; ?>
        <div class="page-content">
            <?= $msg ?>

            <!-- Tabs -->
            <div style="display:flex;gap:8px;margin-bottom:24px;flex-wrap:wrap">
                <a href="?tab=lost"  class="btn <?= $tab==='lost' ?'btn-primary':'btn-light' ?>">🔍 Lost Reports <span class="badge" style="background:rgba(255,255,255,.25);color:inherit;margin-left:4px"><?= $lost_items->num_rows ?></span></a>
                <a href="?tab=found" class="btn <?= $tab==='found'?'btn-success':'btn-light' ?>">📦 Found Reports <span class="badge" style="background:rgba(255,255,255,.25);color:inherit;margin-left:4px"><?= $found_items->num_rows ?></span></a>
                <div style="margin-left:auto">
                    <?php if($tab==='lost'): ?>
                    <a href="/lostfound_relink/user/report_lost.php" class="btn btn-primary">+ New Lost Report</a>
                    <?php else: ?>
                    <a href="/lostfound_relink/user/report_found.php" class="btn btn-success">+ New Found Report</a>
                    <?php endif; ?>
                </div>
            </div>

            <?php if($tab === 'lost'): ?>

            <?php if($lost_items->num_rows === 0): ?>
            <div class="rt-empty">
                <div class="icon">🔍</div>
                <p style="font-size:15px;font-weight:600;margin-bottom:8px">No lost item reports yet</p>
                <p style="font-size:13px;margin-bottom:20px">Report a lost item and we'll help you find it</p>
                <a href="/lostfound_relink/user/report_lost.php" class="btn btn-primary">Report Lost Item</a>
            </div>
            <?php else: ?>
            <div class="report-timeline">
            <?php while($item=$lost_items->fetch_assoc()):
                $step = statusStep($item['status'], $lost_steps);
                $steps = [
                    ['label'=>'Reported',  'icon'=>'📝'],
                    ['label'=>'Matched',   'icon'=>'🤝'],
                    ['label'=>'Returned',  'icon'=>'✅'],
                ];
            ?>
            <div class="rt-card">
                <div class="rt-card-top">
                    <?php if($item['image_path']): ?>
                    <img src="/lostfound_relink/<?= htmlspecialchars($item['image_path']) ?>" class="rt-img" alt="">
                    <?php else: ?>
                    <div class="rt-img-placeholder">🔍</div>
                    <?php endif; ?>
                    <div class="rt-info">
                        <div class="rt-info-top">
                            <div class="rt-name"><?= htmlspecialchars($item['item_name']) ?></div>
                            <span class="badge badge-<?= $item['status'] ?>"><?= $item['status'] ?></span>
                        </div>
                        <div class="rt-meta">
                            <span class="rt-meta-item">📂 <?= htmlspecialchars($item['category']) ?></span>
                            <span class="rt-meta-item">📍 <?= htmlspecialchars($item['location']) ?></span>
                            <?php if($item['date_lost']): ?>
                            <span class="rt-meta-item">📅 Lost: <?= date('M d, Y', strtotime($item['date_lost'])) ?></span>
                            <?php endif; ?>
                        </div>
                        <?php if($item['description']): ?>
                        <div class="rt-desc"><?= htmlspecialchars(substr($item['description'],0,120)) ?><?= strlen($item['description'])>120?'…':'' ?></div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Status Progress -->
                <div class="rt-progress">
                    <div class="rt-progress-label">Status Progress</div>
                    <div class="rt-steps">
                    <?php foreach($steps as $i => $s):
                        $isDone   = $step > $i;
                        $isActive = $step === $i;
                        $isReturn = $item['status']==='returned' && $i===2;
                        $cls = $isReturn ? 'returned' : ($isDone ? 'done' : ($isActive ? 'active' : ''));
                    ?>
                        <div class="rt-step <?= $cls ?>">
                            <div class="rt-step-dot"><?= $isDone||$isReturn ? '✓' : ($i+1) ?></div>
                            <div class="rt-step-label"><?= $s['icon'] ?> <?= $s['label'] ?></div>
                        </div>
                        <?php if($i < count($steps)-1):
                            $lineDone = $step > $i;
                            $lineRet  = $item['status']==='returned' && $i>=1;
                        ?>
                        <div class="rt-step-line <?= $lineRet?'returned':($lineDone?'done':'') ?>"></div>
                        <?php endif; ?>
                    <?php endforeach; ?>
                    </div>
                </div>

                <div class="rt-actions">
                    <span class="rt-date">Reported <?= date('M d, Y', strtotime($item['created_at'])) ?></span>
                    <?php if($item['status'] === 'pending'): ?>
                    <form method="POST" onsubmit="return confirmDelete(this)" data-item="<?= htmlspecialchars($item['item_name']) ?>">
                        <input type="hidden" name="item_id" value="<?= $item['id'] ?>">
                        <button type="submit" name="delete_lost" class="btn btn-sm btn-danger">🗑 Delete</button>
                    </form>
                    <?php else: ?>
                    <span style="font-size:12px;color:var(--text-muted)">🔒 Locked — cannot delete</span>
                    <?php endif; ?>
                </div>
            </div>
            <?php endwhile; ?>
            </div>
            <?php endif; ?>

            <?php else: /* found tab */ ?>

            <?php if($found_items->num_rows === 0): ?>
            <div class="rt-empty">
                <div class="icon">📦</div>
                <p style="font-size:15px;font-weight:600;margin-bottom:8px">No found item reports yet</p>
                <p style="font-size:13px;margin-bottom:20px">Help others by reporting items you've found</p>
                <a href="/lostfound_relink/user/report_found.php" class="btn btn-success">Report Found Item</a>
            </div>
            <?php else: ?>
            <div class="report-timeline">
            <?php while($item=$found_items->fetch_assoc()):
                $step = statusStep($item['status'], $found_steps);
                $steps = [
                    ['label'=>'Reported', 'icon'=>'📝'],
                    ['label'=>'Matched',  'icon'=>'🤝'],
                    ['label'=>'Returned', 'icon'=>'✅'],
                    ['label'=>'Closed',   'icon'=>'🔒'],
                ];
            ?>
            <div class="rt-card">
                <div class="rt-card-top">
                    <?php if($item['image_path']): ?>
                    <img src="/lostfound_relink/<?= htmlspecialchars($item['image_path']) ?>" class="rt-img" alt="">
                    <?php else: ?>
                    <div class="rt-img-placeholder">📦</div>
                    <?php endif; ?>
                    <div class="rt-info">
                        <div class="rt-info-top">
                            <div class="rt-name"><?= htmlspecialchars($item['item_name']) ?></div>
                            <span class="badge badge-<?= $item['status'] ?>"><?= $item['status'] ?></span>
                        </div>
                        <div class="rt-meta">
                            <span class="rt-meta-item">📂 <?= htmlspecialchars($item['category']) ?></span>
                            <span class="rt-meta-item">📍 <?= htmlspecialchars($item['location']) ?></span>
                            <?php if($item['date_found']): ?>
                            <span class="rt-meta-item">📅 Found: <?= date('M d, Y', strtotime($item['date_found'])) ?></span>
                            <?php endif; ?>
                        </div>
                        <?php if($item['description']): ?>
                        <div class="rt-desc"><?= htmlspecialchars(substr($item['description'],0,120)) ?><?= strlen($item['description'])>120?'…':'' ?></div>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="rt-progress">
                    <div class="rt-progress-label">Status Progress</div>
                    <div class="rt-steps">
                    <?php foreach($steps as $i => $s):
                        $isDone   = $step > $i;
                        $isActive = $step === $i;
                        $isReturn = $item['status']==='returned' && $i===2;
                        $cls = $isReturn ? 'returned' : ($isDone ? 'done' : ($isActive ? 'active' : ''));
                    ?>
                        <div class="rt-step <?= $cls ?>">
                            <div class="rt-step-dot"><?= $isDone||$isReturn ? '✓' : ($i+1) ?></div>
                            <div class="rt-step-label"><?= $s['icon'] ?> <?= $s['label'] ?></div>
                        </div>
                        <?php if($i < count($steps)-1):
                            $lineDone = $step > $i;
                            $lineRet  = $item['status']==='returned' && $i>=1;
                        ?>
                        <div class="rt-step-line <?= $lineRet?'returned':($lineDone?'done':'') ?>"></div>
                        <?php endif; ?>
                    <?php endforeach; ?>
                    </div>
                </div>

                <div class="rt-actions">
                    <span class="rt-date">Reported <?= date('M d, Y', strtotime($item['created_at'])) ?></span>
                    <?php if($item['status'] === 'pending'): ?>
                    <form method="POST" onsubmit="return confirmDelete(this)" data-item="<?= htmlspecialchars($item['item_name']) ?>">
                        <input type="hidden" name="item_id" value="<?= $item['id'] ?>">
                        <button type="submit" name="delete_found" class="btn btn-sm btn-danger">🗑 Delete</button>
                    </form>
                    <?php else: ?>
                    <span style="font-size:12px;color:var(--text-muted)">🔒 Locked — cannot delete</span>
                    <?php endif; ?>
                </div>
            </div>
            <?php endwhile; ?>
            </div>
            <?php endif; ?>

            <?php endif; ?>
        </div>
    </div>
</div>
<script src="/lostfound_relink/assets/js/main.js"></script>
</body>
</html>
