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

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require '../vendor/PHPMailer/src/Exception.php';
require '../vendor/PHPMailer/src/PHPMailer.php';
require '../vendor/PHPMailer/src/SMTP.php';

/* ================= SECURITY ================= */
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'hod') {
    header("Location: ../login.php");
    exit();
}

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

/* ================= GET FULL DATA ================= */
$sql = "
SELECT 
    mr.*,

    e.equipment_name,
    e.category,
    e.purchase_date,
    e.next_due_date,
    e.description AS equipment_description,
    e.serial_number,
    e.location,
    e.status AS equipment_status,
    e.image AS equipment_image,
    e.department,

    mreq.issue_description AS request_issue,
    mreq.issue_image,

    u.full_name AS technician_name,
    u.email AS technician_email

FROM maintenance_record mr

JOIN equipment e 
ON mr.equipment_id = e.id

JOIN maintenance_request mreq
ON mr.request_id = mreq.id

JOIN users u 
ON mr.technician_id = u.id

WHERE mr.id = ?
";

$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "i", $id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

$row = mysqli_fetch_assoc($result);

if (!$row) {
    die("Record not found");
}

/* ================= EMAIL ================= */
function sendHODEmail($toEmail, $toName, $subject, $messageBody) {

    $mail = new PHPMailer(true);

    try {
        $mail->isSMTP();
        $mail->Host = 'mail.priorisys.com';
        $mail->SMTPAuth = true;
        $mail->Username = 'support@qrcare.priorisys.com';
        $mail->Password = 'Hifzhan2017';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port = 587;

        $mail->setFrom('support@qrcare.priorisys.com', 'QRCareTrack');
        $mail->addAddress($toEmail, $toName);

        $mail->isHTML(true);
        $mail->Subject = $subject;

        $mail->Body = "
        <div style='font-family:Segoe UI;padding:20px;'>
            <h2>QRCareTrack</h2>
            <p>Hi <b>$toName</b>,</p>
            <p>$messageBody</p>
        </div>";

        $mail->send();

    } catch (Exception $e) {
        error_log($mail->ErrorInfo);
    }
}

/* ================= HANDLE ACTION ================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $next_due_date = !empty($_POST['next_due_date'])
    ? date("Y-m-d H:i:s", strtotime($_POST['next_due_date']))
    : null;
    $action = $_POST['action'];
    $comment = trim($_POST['hod_comment']);
    $now = date("Y-m-d H:i:s");

    if ($action == "approve") {

        $status = "Completed";

        $q = "UPDATE maintenance_record 
              SET status=?, hod_comment=?, updated_at=? 
              WHERE id=?";

        $stmt1 = mysqli_prepare($conn, $q);
        mysqli_stmt_bind_param($stmt1, "sssi", $status, $comment, $now, $id);
        mysqli_stmt_execute($stmt1);

        // equipment back to active
        $q2 = "
                UPDATE equipment
                SET
                    status='Active',
                    next_due_date=?
                WHERE id=?
                ";
                
                $stmt2 = mysqli_prepare($conn, $q2);
                mysqli_stmt_bind_param(
                    $stmt2,
                    "si",
                    $next_due_date,
                    $row['equipment_id']
                );
                mysqli_stmt_execute($stmt2);

        sendHODEmail(
            $row['technician_email'],
            $row['technician_name'],
            "Maintenance Approved",
            "Work for <b>{$row['equipment_name']}</b> has been APPROVED."
        );

    } else {

        $status = "HOD Rejected";

        $q = "UPDATE maintenance_record 
              SET status=?, hod_comment=?, updated_at=? 
              WHERE id=?";

        $stmt1 = mysqli_prepare($conn, $q);
        mysqli_stmt_bind_param($stmt1, "sssi", $status, $comment, $now, $id);
        mysqli_stmt_execute($stmt1);

        sendHODEmail(
            $row['technician_email'],
            $row['technician_name'],
            "Maintenance Rejected",
            "Work for <b>{$row['equipment_name']}</b> has been REJECTED."
        );
    }

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

<!DOCTYPE html>
<html>
<head>
<title>HOD Review</title>

<style>
body{
    background:#f4f6f8;
    font-family:Arial;
}

/* MAIN WRAPPER (IMPORTANT FOR SIDEBAR) */
.main{
    margin-left:260px;
    padding:20px;
}

/* LIMIT WIDTH SUPAYA TAK LEBAR SANGAT */
.page-wrapper{
    max-width:1000px;
    margin:auto;
}

/* GRID */
.container-grid{
    display:flex;
    gap:15px;
    margin-bottom:15px;
}

/* BOX STYLE COMPACT */
.box{
    flex:1;
    background:#fff;
    padding:12px;
    border-radius:10px;
    box-shadow:0 2px 8px rgba(0,0,0,0.06);
    font-size:14px;
}

/* IMAGE SMALLER */
.box img{
    width:100%;
    max-width:160px;
    border-radius:8px;
    margin-top:8px;
}

/* TEXT COMPACT */
h2{
    margin-bottom:10px;
}

h3{
    margin:10px 0;
    font-size:15px;
}

/* FORM */
textarea{
    width:100%;
    min-height:100px;
    padding:8px;
    border-radius:8px;
    border:1px solid #ddd;
    font-size:13px;
}

/* BUTTON */
.btn{
    padding:8px 12px;
    border:none;
    border-radius:6px;
    color:#fff;
    cursor:pointer;
    font-size:13px;
}

.approve{ background:green; }
.reject{ background:red; }

.box p{
    margin:6px 0;
    font-size:13px;
}

hr{
    margin:10px 0;
    border:0.5px solid #eee;
}

/* APPROVAL BOX */
.approval-box{
    background:#fff;
    padding:12px;
    border-radius:10px;
    box-shadow:0 2px 8px rgba(0,0,0,0.06);
}
</style>

</head>

<body>

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

<div class="main">

<h2>HOD Approval</h2>

<!-- ================= GRID ================= -->
<div class="container-grid">

    <!-- LEFT -->
    <div class="box">

        <h3>Equipment</h3>

        <?php if (!empty($row['equipment_image'])): ?>
            <img src="../assets/images/<?= htmlspecialchars($row['equipment_image']) ?>">
        <?php endif; ?>

        <p><b>Name:</b> <?= htmlspecialchars($row['equipment_name']) ?></p>
        <p><b>Category:</b> <?= htmlspecialchars($row['category']) ?></p>
        <p><b>Serial:</b> <?= htmlspecialchars($row['serial_number']) ?></p>
        <p><b>Location:</b> <?= htmlspecialchars($row['location']) ?></p>
        <p><b>Status:</b> <?= htmlspecialchars($row['equipment_status']) ?></p>

        <hr>

        <h3>Issue</h3>

        <?php if (!empty($row['issue_image'])): ?>
            <img src="../assets/issue_images/<?= htmlspecialchars($row['issue_image']) ?>">
        <?php endif; ?>

        <p><?= nl2br(htmlspecialchars($row['request_issue'])) ?></p>

    </div>

    <!-- RIGHT -->
    <div class="box">

        <h3>Maintenance</h3>

        <p><b>Technician:</b> <?= htmlspecialchars($row['technician_name']) ?></p>
        <p><b>Status:</b> <?= htmlspecialchars($row['status']) ?></p>

        <p><b>Work Done:</b></p>
        <p><?= nl2br(htmlspecialchars($row['description'])) ?></p>

        <p><b>Progress:</b></p>
        <p><?= nl2br(htmlspecialchars($row['technician_description'])) ?></p>

        <?php if (!empty($row['proof_image'])): ?>
            <img src="../assets/maintenance_proof/<?= htmlspecialchars($row['proof_image']) ?>">
        <?php endif; ?>

    </div>

</div>

<!-- ================= APPROVAL ================= -->
<div class="approval-box">

    <h3>HOD Approval</h3>

    <form method="POST">

    <label>Next Maintenance Date</label>

<input
    type="text"
    value="<?= !empty($row['next_due_date']) ? date('d M Y h:i A', strtotime($row['next_due_date'])) : 'Not Scheduled' ?>"
    readonly
    style="
        width:100%;
        padding:10px;
        border:1px solid #ddd;
        border-radius:8px;
        margin-bottom:15px;
        background:#f5f5f5;
        color:#555;
    "
>

    <label>Comment</label>
    <textarea name="hod_comment" required></textarea>

    <br><br>

    <button class="btn approve" name="action" value="approve">
        Approve
    </button>

    <button class="btn reject" name="action" value="reject">
        Reject
    </button>

</form>

</div>

</div>

</body>
</html>