<?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 request_desc,
    mr.technician_description,
    mr.status AS maintenance_status,
    mr.maintenance_date,
    mr.updated_at,
    mr.proof_image,
    mr.hod_comment,

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

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['technician_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
        technician_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'];
    
    $next_due_date = !empty($_POST['next_due_date'])
    ? date("Y-m-d H:i:s", strtotime($_POST['next_due_date']))
    : null;
    
    /* 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)) {

    // Update next maintenance date
    $eqUpdate = mysqli_prepare(
        $conn,
        "UPDATE equipment
         SET next_due_date = ?
         WHERE id = ?"
    );

    mysqli_stmt_bind_param(
        $eqUpdate,
        "si",
        $next_due_date,
        $row['equipment_id']
    );

    mysqli_stmt_execute($eqUpdate);

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

/* NEXT MAINTENANCE CARD */

.next-maintenance-card{
    background: linear-gradient(
        135deg,
        #eef8ff,
        #f8fcff
    );

    border: 1px solid #dbeafe;

    border-left: 5px solid #2563eb;

    padding: 18px;

    border-radius: 12px;

    margin-bottom: 20px;
}

.next-label{
    display:block;
    font-size:15px;
    font-weight:700;
    color:#1e40af;
    margin-bottom:10px;
}

.next-date-input{
    width:100%;
    padding:12px;
    border:1px solid #cbd5e1;
    border-radius:10px;
    font-size:14px;
    background:#fff;
    transition:0.3s;
}

.next-date-input:focus{
    border-color:#2563eb;
    box-shadow:0 0 0 4px rgba(37,99,235,0.15);
    outline:none;
}

.next-hint{
    display:block;
    margin-top:8px;
    color:#64748b;
    font-size:12px;
}

</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>

<?php if (
    $row['maintenance_status'] == 'HOD Rejected'
    && !empty($row['hod_comment'])
): ?>

<div style="
    margin-top:15px;
    background:#fee2e2;
    border-left:4px solid #dc2626;
    padding:12px;
    border-radius:8px;
">

    <strong>HOD Rejection Comment:</strong><br>

    <?= nl2br(htmlspecialchars($row['hod_comment'])) ?>

</div>

<?php endif; ?>

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

    <?= !empty($row['next_due_date'])
    ? date("d M Y h:i A", strtotime($row['next_due_date']))
    : 'Not Scheduled' ?>
</div>

<div>
    <strong>Issue Description (Request):</strong><br>
    <?= nl2br(htmlspecialchars($row['request_desc'])) ?>
</div>

</div>

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

<!-- DESCRIPTION -->
<div class="form-group">
    <label>Next Maintenance Date</label>

    <?php
$tomorrow = date(
    'Y-m-d\TH:i',
    strtotime('+1 day')
);
?>

<div class="next-maintenance-card">

    <label class="next-label">
        📅 Next Maintenance Date
    </label>

    <input
        type="datetime-local"
        class="next-date-input"
        name="next_due_date"
        min="<?= $tomorrow ?>"
        value="<?= !empty($row['next_due_date']) ? date('Y-m-d\TH:i', strtotime($row['next_due_date'])) : '' ?>"
        required
    >

    <small class="next-hint">
        Select a future maintenance schedule (tomorrow onwards).
    </small>

</div>
</div>

<div class="form-group">

<label>Description / Progress</label>

<textarea name="technician_description"><?= 
htmlspecialchars($row['technician_description']) 
?></textarea><?= 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>