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

$page_title = 'Report Found Item';
$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $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']);
    $uid         = $_SESSION['user_id'];
    $image_path  = '';
    $finder_photo = '';

    // Upload item image
    $contact_number = sanitize($conn, $_POST['contact_number']);

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

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

    if (!$msg) {
        $user_gender = $conn->query("SELECT gender FROM users WHERE id=$uid")->fetch_assoc()['gender'] ?? null;
        $gender_val = $user_gender ? "'$user_gender'" : 'NULL';
        $conn->query("INSERT INTO found_items (user_id, item_name, description, category, location, date_found, image_path, finder_photo, surrenderer_gender, contact_number) VALUES ($uid,'$item_name','$description','$category','$location','$date_found','$image_path','$finder_photo',$gender_val,'$contact_number')");
        $new_id = $conn->insert_id;
        runMatchingAlgorithm($conn, null, $new_id);
        $msg = '<div class="alert alert-success">✅ Found item reported successfully! Thank you for helping others.</div>';
    }
}

$categories = $conn->query("SELECT name FROM categories ORDER BY name");
$user_phone = $conn->query("SELECT phone FROM users WHERE id={$_SESSION['user_id']}")->fetch_assoc()['phone'] ?? '';
?>
<!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">
</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 ?>

            <div class="rf-wrapper">
                <!-- Sidebar Info -->
                <div class="rf-sidebar">
                    <div class="rf-info-card rf-info-found">
                        <div class="rf-info-icon">📦</div>
                        <h3>Reporting a Found Item</h3>
                        <p>Thank you for helping! Your report will be matched against lost item reports automatically.</p>
                    </div>
                    <div class="rf-tips">
                        <div class="rf-tip">
                            <span class="rf-tip-icon">✏️</span>
                            <div><strong>Describe clearly</strong><br><small>Include brand, color, and unique features</small></div>
                        </div>
                        <div class="rf-tip">
                            <span class="rf-tip-icon">📍</span>
                            <div><strong>Exact location</strong><br><small>Where exactly did you find it?</small></div>
                        </div>
                        <div class="rf-tip">
                            <span class="rf-tip-icon">📷</span>
                            <div><strong>Upload photos</strong><br><small>Item photo + your photo speeds up verification</small></div>
                        </div>
                        <div class="rf-tip">
                            <span class="rf-tip-icon">✅</span>
                            <div><strong>Admin will verify</strong><br><small>A match will be confirmed before notifying the owner</small></div>
                        </div>
                    </div>
                </div>

                <!-- Form -->
                <div class="rf-form-card">
                    <div class="rf-form-header rf-form-header--found">
                        <div class="rf-form-header-icon">📦</div>
                        <div>
                            <h2>Report a Found Item</h2>
                            <p>All fields marked with <span style="color:#ef4444">*</span> are required</p>
                        </div>
                    </div>

                    <form method="POST" enctype="multipart/form-data" class="rf-form">

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

                        <div class="form-group">
                            <label>Item Name <span class="rf-required">*</span></label>
                            <input type="text" name="item_name" class="form-control rf-input" placeholder="e.g. Black Wallet, Samsung Galaxy A54" required>
                        </div>

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

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

                        <div class="form-group">
                            <label>Description <span class="rf-optional">(optional but recommended)</span></label>
                            <textarea name="description" class="form-control rf-input" rows="4" placeholder="Describe the item: color, brand, size, distinguishing marks, contents..."></textarea>
                        </div>

                        <div class="form-group">
                            <label>Contact Number <span class="rf-required">*</span></label>
                            <input type="text" name="contact_number" class="form-control rf-input" placeholder="09XXXXXXXXX" value="<?= htmlspecialchars($user_phone) ?>" required>
                        </div>

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

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

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

                        <div class="rf-notice">
                            💡 <strong>Why upload your photo?</strong> It helps the admin and item owner verify that the right person is returning the item, making the process faster and more trustworthy.
                        </div>

                        <div class="rf-form-actions">
                            <button type="submit" class="btn btn-success btn-lg rf-submit-btn">📦 Submit Found Report</button>
                            <a href="/lostfound_relink/user/dashboard.php" class="btn btn-light">Cancel</a>
                        </div>

                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="/lostfound_relink/assets/js/main.js"></script>
</body>
</html>
