<?php
session_start();
require_once __DIR__ . "/../config/db.php";

if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$equipment_id = intval($_GET['id'] ?? 0);

if ($equipment_id <= 0) {
    die("Invalid equipment selected.");
}

/* =========================
   TRACK ORIGINAL SOURCE FOR BACK BUTTON
========================= */
// Check if the user came from report_issue.php or if it's already preserved via POST
$is_from_hub = false;
if (isset($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], 'report_issue.php') !== false) {
    $is_from_hub = true;
} elseif (isset($_POST['came_from_hub']) && $_POST['came_from_hub'] === '1') {
    $is_from_hub = true;
}

// Set up the dynamic URL for the back button
$back_url = $is_from_hub 
    ? "report_issue.php" 
    : "../equipment/equipment_details.php?id=" . $equipment_id;

/* =========================
   FETCH EQUIPMENT
========================= */
$stmt = mysqli_prepare($conn, "
    SELECT e.*, d.name AS department_name
    FROM equipment e
    LEFT JOIN departments d ON e.department_id = d.id
    WHERE e.id = ?
");

mysqli_stmt_bind_param($stmt, "i", $equipment_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$equipment = mysqli_fetch_assoc($result);

if (!$equipment) {
    die("Equipment not found.");
}

/* =========================
   HANDLE SUBMIT
========================= */
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $urgency = intval($_POST['urgency'] ?? 5);
    $description = trim($_POST['issue_description'] ?? '');
    $imageName = null;

    if ($description === '') {
        $errors[] = "Please describe the issue.";
    }

    if (!empty($_FILES['issue_image']['name'])) {
        $dir = __DIR__ . "/../assets/issue_images/";
        if (!is_dir($dir)) mkdir($dir, 0777, true);

        $imageName = time() . "_" . basename($_FILES['issue_image']['name']);
        move_uploaded_file($_FILES['issue_image']['tmp_name'], $dir . $imageName);
    }

    if (empty($errors)) {
        $stmt = mysqli_prepare($conn, "
            INSERT INTO maintenance_request
            (equipment_id, requested_by, issue_description, status, created_at, urgency, issue_image)
            VALUES (?, ?, ?, 'Reported', NOW(), ?, ?)
        ");

        mysqli_stmt_bind_param($stmt, "iisis",
            $equipment_id,
            $user_id,
            $description,
            $urgency,
            $imageName
        );

        if (mysqli_stmt_execute($stmt)) {
            // Submission always redirects to maintenance dashboard page
            header("Location: ../maintenance.php?msg=success");
            exit();
        } else {
            $errors[] = "Failed to submit report.";
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Report Issue</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">

<style>
/* BODY */
body{
    margin:0;
    font-family:"Segoe UI", sans-serif;
    background:#f6fffe;
}

/* WRAPPER */
.wrapper{
    max-width:780px;
    margin:30px auto;
    padding:20px;
}

/* CARD */
.card{
    background:white;
    border-radius:14px;
    box-shadow:0 2px 12px rgba(0,0,0,0.06);
    padding:22px;
    margin-bottom:18px;
}

/* HEADER STYLE */
.header{
    border-top:6px solid #14b8a6;
}

/* HEADER TITLE & BACK ALIGNMENT */
.title-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
}

h1,h2{
    margin:0;
    color:#0f766e;
}

p{
    color:#666;
    margin-top:6px;
    margin-bottom:15px;
}

/* BACK BUTTON */
.back-btn {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    text-decoration: none;
    background: #64748b;
    color: white;
    padding: 8px 16px;
    border-radius: 8px;
    font-weight: 600;
    font-size: 14px;
    transition: background 0.2s;
}
.back-btn:hover {
    background: #475569;
}

/* EQUIPMENT IMAGE */
.equip-card img{
    width:140px;
    height:140px;
    object-fit:cover;
    display:block;
    margin:10px auto 15px;
    border-radius:50%;
    border:3px solid #14b8a6;
    box-shadow:0 4px 12px rgba(0,0,0,0.08);
}

/* INFO GRID */
.info{
    font-size:14px;
    margin:6px 0;
}

.info span{
    color:#0f766e;
    font-weight:600;
}

/* FORM ELEMENTS */
label{
    font-weight:600;
    color:#0f766e;
    display:block;
    margin:12px 0 6px;
}

textarea, input[type="file"], input[type="range"]{
    width:100%;
    box-sizing: border-box;
}

textarea{
    padding:12px;
    border-radius:10px;
    border:1px solid #ddd;
    resize:none;
}

/* RANGE AND LABELS */
.range-box{
    background:#ecfeff;
    padding:15px;
    border-radius:10px;
    border: 1px solid #cffafe;
}
.urgency-indicator {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 10px;
    font-weight: bold;
    font-size: 14px;
}
.urgency-badge {
    padding: 4px 10px;
    border-radius: 6px;
    color: white;
}

/* BUTTON */
button{
    width:100%;
    padding:14px;
    border:none;
    border-radius:10px;
    background:#14b8a6;
    color:white;
    font-weight:bold;
    cursor:pointer;
    font-size:15px;
}

button:hover{
    background:#0f766e;
}

/* ERROR */
.error{
    background:#fee2e2;
    color:#b91c1c;
    padding:12px;
    border-radius:10px;
    margin-bottom:15px;
}

@media(max-width:768px){
    .wrapper{ margin:10px; }
}
</style>
</head>

<body>

<div class="wrapper">

<div class="card equip-card header">
    <div class="title-container">
        <h2>Equipment Information</h2>
        <a href="<?= $back_url ?>" class="back-btn">
            <i class="fas fa-arrow-left"></i> Back
        </a>
    </div>
    <p>Details of selected equipment before reporting issue</p>

    <?php if(!empty($equipment['image'])): ?>
        <img src="../assets/uploads/<?= htmlspecialchars($equipment['image']) ?>">
    <?php else: ?>
        <img src="../assets/uploads/placeholder.png">
    <?php endif; ?>

    <div class="info"><span>Name:</span> <?= htmlspecialchars($equipment['equipment_name']) ?></div>
    <div class="info"><span>Category:</span> <?= htmlspecialchars($equipment['category']) ?></div>
    <div class="info"><span>Serial:</span> <?= htmlspecialchars($equipment['serial_number']) ?></div>
    <div class="info"><span>Location:</span> <?= htmlspecialchars($equipment['location'] ?? '-') ?></div>
    <div class="info"><span>Status:</span> <?= htmlspecialchars($equipment['status']) ?></div>
    <div class="info"><span>Department:</span> <?= htmlspecialchars($equipment['department_name']) ?></div>
</div>

<?php if(!empty($errors)): ?>
<div class="error">
    <?php foreach($errors as $e) echo $e."<br>"; ?>
</div>
<?php endif; ?>

<div class="card">
    <h2>Report Issue</h2>
    <p>Please fill in the details below</p>

    <form method="POST" enctype="multipart/form-data">
        <input type="hidden" name="came_from_hub" value="<?= $is_from_hub ? '1' : '0' ?>">

        <label>Urgency Level</label>
        <div class="range-box">
            <input type="range" id="urgencyRange" name="urgency" min="1" max="10" value="5" oninput="updateUrgencyLabel(this.value)">
            
            <div class="urgency-indicator">
                <span>Selected Level: <span id="levelValue" style="color:#0f766e;">5</span></span>
                <span id="urgencyBadge" class="urgency-badge">Loading...</span>
            </div>
        </div>

        <label>Issue Description</label>
        <textarea name="issue_description" rows="5" placeholder="Describe the issue..." required></textarea>

        <label>Upload Image (optional)</label>
        <input type="file" name="issue_image" accept="image/*">

        <br><br>
        <button type="submit">Submit Report</button>
    </form>
</div>

</div>

<script>
function updateUrgencyLabel(val) {
    const valueEl = document.getElementById('levelValue');
    const badgeEl = document.getElementById('urgencyBadge');
    valueEl.textContent = val;
    
    let levelNum = parseInt(val);
    
    if (levelNum >= 1 && levelNum <= 3) {
        badgeEl.textContent = "1-3: Low / Cosmetic / Routine";
        badgeEl.style.background = "#2ecc71"; // Green
    } else if (levelNum >= 4 && levelNum <= 7) {
        badgeEl.textContent = "4-7: Medium / Impaired / Minor Malfunction";
        badgeEl.style.background = "#f39c12"; // Amber/Orange
    } else {
        badgeEl.textContent = "8-10: High / Critical Breakage / Safety Risk";
        badgeEl.style.background = "#ef4444"; // Red
    }
}

// Initial fire on document ready
updateUrgencyLabel(document.getElementById('urgencyRange').value);
</script>

</body>
</html>