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

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

$user_id = $_SESSION['user_id'];

if (!isset($_GET['id'])) {
    die("Invalid request.");
}

$record_id = intval($_GET['id']);

/* =========================================
   GET RECORD DETAILS
========================================= */

$sql = "
SELECT 
    mr.id AS record_id,
    mr.description AS maintenance_desc,
    mr.status AS maintenance_status,
    mr.maintenance_date,
    mr.updated_at,
    mr.proof_image,

    e.id AS equipment_id,
    e.equipment_name,
    e.category

FROM maintenance_record mr

JOIN equipment e 
ON mr.equipment_id = e.id

WHERE mr.id = ?
AND mr.technician_id = ?
";

$stmt = mysqli_prepare($conn, $sql);

mysqli_stmt_bind_param(
    $stmt,
    "ii",
    $record_id,
    $user_id
);

mysqli_stmt_execute($stmt);

$result = mysqli_stmt_get_result($stmt);

if (!$row = mysqli_fetch_assoc($result)) {
    die("Record not found or you are not assigned to this record.");
}

$message = "";

/* =========================================
   UPDATE RECORD
========================================= */

if (isset($_POST['update_record'])) {

    $new_desc = trim($_POST['description']);

    $updated_at = date("Y-m-d H:i:s");

    $proof_image = $row['proof_image'];

    /* IMAGE UPLOAD */
    if (!empty($_FILES['proof_image']['name'])) {

        $uploadDir = "../assets/maintenance_proof/";

        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        $fileName = time() . "_" .
        basename($_FILES['proof_image']['name']);

        $targetFile = $uploadDir . $fileName;

        if (
            move_uploaded_file(
                $_FILES['proof_image']['tmp_name'],
                $targetFile
            )
        ) {
            $proof_image = $fileName;
        }
    }

    $update = "
    UPDATE maintenance_record
    SET
        description = ?,
        updated_at = ?,
        proof_image = ?
    WHERE id = ?
    ";

    $stmt2 = mysqli_prepare($conn, $update);

    mysqli_stmt_bind_param(
        $stmt2,
        "sssi",
        $new_desc,
        $updated_at,
        $proof_image,
        $record_id
    );

    if (mysqli_stmt_execute($stmt2)) {

        header("Location: ../maintenance.php?update=success");
        exit();

    } else {

        $message = "Error updating record.";
    }
}

/* =========================================
   SUBMIT TO HOD REVIEW
========================================= */

if (isset($_POST['submit_review'])) {

    $review_status = "HOD Review";

    $updated_at = date("Y-m-d H:i:s");

    $maintenance_date = date("Y-m-d");

    $proof_image = $row['proof_image'];

    /* IMAGE UPLOAD */
    if (!empty($_FILES['proof_image']['name'])) {

        $uploadDir = "../assets/maintenance_proof/";

        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        $fileName = time() . "_" .
        basename($_FILES['proof_image']['name']);

        $targetFile = $uploadDir . $fileName;

        if (
            move_uploaded_file(
                $_FILES['proof_image']['tmp_name'],
                $targetFile
            )
        ) {
            $proof_image = $fileName;
        }
    }

    $update = "
    UPDATE maintenance_record
    SET
        status = ?,
        maintenance_date = ?,
        updated_at = ?,
        proof_image = ?
    WHERE id = ?
    ";

    $stmt2 = mysqli_prepare($conn, $update);

    mysqli_stmt_bind_param(
        $stmt2,
        "ssssi",
        $review_status,
        $maintenance_date,
        $updated_at,
        $proof_image,
        $record_id
    );

    if (mysqli_stmt_execute($stmt2)) {

        header("Location: ../maintenance.php?review=success");
        exit();

    } else {

        $message = "Error submitting for HOD review.";
    }
}
?>

<!DOCTYPE html>
<html>

<head>

<title>Edit Maintenance Record - QRCareTrack</title>

<link rel="stylesheet" href="../assets/style.css">
<link rel="stylesheet" href="../assets/maintenance.css">

<style>

.card-details {
    max-width: 700px;
    margin: 30px auto;
    background: #fff;
    padding: 35px;
    border-radius: 14px;
    box-shadow: 0 10px 25px rgba(0,0,0,0.08);
}

.card-details h2 {
    margin-bottom: 25px;
}

.form-group {
    margin-bottom: 18px;
}

label {
    font-weight: 600;
    display: block;
    margin-bottom: 8px;
}

textarea,
input[type="file"] {
    width: 100%;
    padding: 12px;
    border: 1px solid #ddd;
    border-radius: 8px;
}

textarea{
    min-height:140px;
    resize:vertical;
}

.status-badge{
    display:inline-block;
    padding:6px 12px;
    border-radius:6px;
    background:#f39c12;
    color:#fff;
    font-size:13px;
    font-weight:600;
}

.btn {
    padding: 12px 20px;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    font-weight: 600;
    margin-top: 10px;
    text-decoration:none;
    display:inline-block;
}

.btn-update {
    background: #2bbbad;
    color: #fff;
}

.btn-review {
    background: #2563eb;
    color: #fff;
    margin-left: 10px;
}

.btn-back {
    background: #e74c3c;
    color: #fff;
    margin-left: 10px;
}

.btn-update:hover {
    background: #239c92;
}

.btn-review:hover {
    background: #1d4ed8;
}

.message {
    background: #e8f8f5;
    padding: 10px;
    border-radius: 8px;
    margin-bottom: 15px;
}

.proof-preview img {
    width: 220px;
    border-radius: 8px;
    margin-top: 10px;
    border:1px solid #ddd;
}

.info-box{
    background:#f8f9fa;
    padding:14px;
    border-radius:10px;
    margin-bottom:20px;
    line-height:1.8;
}

</style>

</head>

<body>

<?php include "../includes/sidebar.php"; ?>

<div class="main">

<div class="card-details">

<h2>Edit Maintenance Record</h2>

<?php if ($message): ?>

<div class="message">

    <?= htmlspecialchars($message) ?>

</div>

<?php endif; ?>

<!-- INFO -->

<div class="info-box">

<div>
    <strong>Equipment:</strong>
    <?= htmlspecialchars($row['equipment_name']) ?>
</div>

<div>
    <strong>Category:</strong>
    <?= htmlspecialchars($row['category']) ?>
</div>

<div>
    <strong>Status:</strong>

    <span class="status-badge">
        <?= htmlspecialchars($row['maintenance_status']) ?>
    </span>
</div>

<div>
    <strong>Maintenance Date:</strong>

    <?= $row['maintenance_date']
    ? date("d M Y", strtotime($row['maintenance_date']))
    : '-' ?>
</div>

</div>

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

<!-- DESCRIPTION -->

<div class="form-group">

<label>Description / Progress</label>

<textarea name="description"><?= htmlspecialchars($row['maintenance_desc']) ?></textarea>

</div>

<!-- IMAGE -->

<div class="form-group">

<label>Proof Image</label>

<input type="file"
name="proof_image"
accept="image/*">

<?php if (!empty($row['proof_image'])): ?>

<div class="proof-preview">

<img src="../assets/maintenance_proof/<?= $row['proof_image'] ?>">

</div>

<?php endif; ?>

</div>

<!-- BUTTONS -->

<button type="submit"
name="update_record"
class="btn btn-update">

    Save Progress

</button>

<?php if($row['maintenance_status'] != 'Completed'): ?>

<button type="submit"
name="submit_review"
class="btn btn-review">

    Submit to HOD Review

</button>

<?php endif; ?>

<a href="record_details.php?id=<?= $row['record_id'] ?>"
class="btn btn-back">

    Back

</a>

</form>

</div>

</div>

</body>
</html>