<?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 RECORD ================= */
$sql = "
SELECT 
    mr.*,
    e.id AS equipment_id,
    e.equipment_name,
    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 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);

/* ================= EMAIL FUNCTION ================= */
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'; // 🔴 PUT YOUR PASSWORD
        $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 Notification</h2>
            <p>Hi <b>$toName</b>,</p>
            <p>$messageBody</p>
            <br>
            <p style='color:#888;font-size:12px;'>This is an automated message.</p>
        </div>
        ";

        $mail->AltBody = strip_tags($messageBody);

        $mail->SMTPOptions = [
            'ssl' => [
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            ]
        ];

        $mail->send();
    } catch (Exception $e) {
        error_log("Email failed: " . $mail->ErrorInfo);
    }
}

/* ================= HANDLE ACTION ================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $action = $_POST['action'];
    $comment = trim($_POST['hod_comment']);
    $now = date("Y-m-d H:i:s");

    if ($action == "approve") {

        $status = "Completed";

        // update maintenance
        $q1 = "UPDATE maintenance_record SET status=?, hod_comment=?, updated_at=? WHERE id=?";
        $stmt1 = mysqli_prepare($conn, $q1);
        mysqli_stmt_bind_param($stmt1, "sssi", $status, $comment, $now, $id);
        mysqli_stmt_execute($stmt1);

        // update equipment → ACTIVE
        $q2 = "UPDATE equipment SET status='Active' WHERE id=?";
        $stmt2 = mysqli_prepare($conn, $q2);
        mysqli_stmt_bind_param($stmt2, "i", $row['equipment_id']);
        mysqli_stmt_execute($stmt2);

        // email
        sendHODEmail(
            $row['technician_email'],
            $row['technician_name'],
            "Maintenance Approved",
            "Your maintenance request for <b>{$row['equipment_name']}</b> has been <b>APPROVED</b> by HOD.<br><br>Comment: $comment"
        );

    } else {

        $status = "HOD Rejected";

        $q1 = "UPDATE maintenance_record SET status=?, hod_comment=?, updated_at=? WHERE id=?";
        $stmt1 = mysqli_prepare($conn, $q1);
        mysqli_stmt_bind_param($stmt1, "sssi", $status, $comment, $now, $id);
        mysqli_stmt_execute($stmt1);

        // email
        sendHODEmail(
            $row['technician_email'],
            $row['technician_name'],
            "Maintenance Rejected",
            "Your maintenance request for <b>{$row['equipment_name']}</b> has been <b>REJECTED</b> by HOD.<br><br>Comment: $comment"
        );
    }

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

<!DOCTYPE html>
<html>
<head>
    <title>HOD Review</title>
    <link rel="stylesheet" href="../assets/style.css">

    <style>
        .box { max-width:700px; margin:30px auto; background:#fff; padding:25px; border-radius:10px; }
        textarea { width:100%; min-height:120px; padding:10px; }
        .btn { padding:10px 15px; border:none; border-radius:6px; color:#fff; cursor:pointer; }
        .approve { background:green; }
        .reject { background:red; }
    </style>
</head>

<body>

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

<div class="main">

<div class="box">

    <h2>HOD Approval</h2>

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

    <form method="POST">

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

        <br><br>

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

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

    </form>

</div>

</div>

</body>
</html>