<?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.");
}

/* =========================
   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)) {
            header("Location: ../maintenance.php?msg=success");
            exit();
        } else {
            $errors[] = "Failed to submit report.";
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Report Issue</title>

<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;
}

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

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

/* EQUIPMENT IMAGE (SMALL PROFILE STYLE) */
.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"]{
    width:100%;
}

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

/* RANGE */
.range-box{
    background:#ecfeff;
    padding:12px;
    border-radius:10px;
}

/* 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;
}

/* RESPONSIVE */
@media(max-width:768px){
    .wrapper{ margin:10px; }
}

</style>

</head>

<body>

<div class="wrapper">

<!-- =========================
     EQUIPMENT CARD (TOP)
========================= -->
<div class="card equip-card header">

<h2>Equipment Information</h2>
<p>Details of selected equipment before reporting issue</p>

<?php if(!empty($equipment['image'])): ?>
    <img src="../assets/images/<?= htmlspecialchars($equipment['image']) ?>">
<?php else: ?>
    <img src="../assets/images/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>

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

<!-- =========================
     FORM CARD (BOTTOM)
========================= -->
<div class="card">

<h2>Report Issue</h2>
<p>Please fill in the details below</p>

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

<label>Urgency Level</label>
<div class="range-box">
    <input type="range" name="urgency" min="1" max="10" value="5">
</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>

</body>
</html>