<?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';

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

$user_id = $_SESSION['user_id'];
$role = $_SESSION['role'];

$errors = [];
$success = "";

/* =========================
   Fetch equipment list
========================= */
$equipments = [];
$equipResult = mysqli_query($conn, "SELECT * FROM equipment ORDER BY equipment_name ASC");
while($eq = mysqli_fetch_assoc($equipResult)) {
    $equipments[] = $eq;
}

/* =========================
   Email helper functions
========================= */
function sendEmail($toEmail, $toName, $subject, $htmlBody, $altBody = "") {
    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host       = 'smtp.gmail.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'hifzhanfatihin30@gmail.com'; // Your Gmail
        $mail->Password   = 'ntqx vlyx slsw kuos';        // App Password
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = 587;

        $mail->setFrom('hifzhanfatihin30@gmail.com', 'QRCareTrack');
        $mail->addAddress($toEmail, $toName);

        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $htmlBody;
        $mail->AltBody = $altBody;

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

        return $mail->send();
    } catch (Exception $e) {
        error_log("Mailer Error: " . $mail->ErrorInfo);
        return false;
    }
}

/* =========================
   Handle form submission
========================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $equipment_id = intval($_POST['equipment_id'] ?? 0);
    $urgency = intval($_POST['urgency'] ?? 5);
    $description = trim($_POST['issue_description'] ?? '');

    // Validation
    if ($equipment_id <= 0) $errors[] = "Please select an equipment.";
    if ($description === "") $errors[] = "Please describe the issue.";
    if ($urgency < 1 || $urgency > 10) $errors[] = "Invalid urgency selected.";

    if (empty($errors)) {
        $stmt = mysqli_prepare($conn, "INSERT INTO maintenance_request (equipment_id, requested_by, issue_description, status, created_at, urgency) VALUES (?, ?, ?, 'Reported', NOW(), ?)");
        mysqli_stmt_bind_param($stmt, "iisi", $equipment_id, $user_id, $description, $urgency);

        if (mysqli_stmt_execute($stmt)) {

            /* =========================
               Fetch user, equipment, department info
            ========================== */
            $userQ = mysqli_query($conn, "SELECT full_name, email FROM users WHERE id=$user_id");
            $userData = mysqli_fetch_assoc($userQ);

            $eqQ = mysqli_query($conn, "SELECT equipment_name, department_id FROM equipment WHERE id=$equipment_id");
            $eqData = mysqli_fetch_assoc($eqQ);

            $deptQ = mysqli_query($conn, "SELECT name FROM departments WHERE id=".$eqData['department_id']);
            $deptData = mysqli_fetch_assoc($deptQ);

            $hodQ = mysqli_query($conn, "SELECT full_name, email FROM users WHERE role='hod' AND department_id=".$eqData['department_id']);

            $descSafe = htmlspecialchars($description);

            /* =========================
               Send email to user
            ========================== */
            $subjectUser = "Maintenance Request Submitted - QRCareTrack";
            $htmlUser = "
                <div style='font-family:Segoe UI,sans-serif; max-width:600px; margin:auto; padding:20px; border:1px solid #ddd; border-radius:8px;'>
                    <h2>Maintenance Request Submitted</h2>
                    <p>Hi {$userData['full_name']},</p>
                    <p>Your request for <strong>{$eqData['equipment_name']}</strong> has been submitted successfully.</p>
                    <p><strong>Department:</strong> {$deptData['name']}<br>
                       <strong>Urgency:</strong> $urgency<br>
                       <strong>Description:</strong> $descSafe</p>
                    <p>We will update you once the maintenance is processed.</p>
                </div>";
            sendEmail($userData['email'], $userData['full_name'], $subjectUser, $htmlUser, "Your request has been submitted.");

            /* =========================
               Send email to HOD(s)
            ========================== */
            while($hod = mysqli_fetch_assoc($hodQ)) {
                $subjectHod = "New Maintenance Request - QRCareTrack";
                $htmlHod = "
                    <div style='font-family:Segoe UI,sans-serif; max-width:600px; margin:auto; padding:20px; border:1px solid #ddd; border-radius:8px;'>
                        <h2>New Maintenance Request</h2>
                        <p>Hi {$hod['full_name']},</p>
                        <p>A new maintenance request has been submitted.</p>
                        <p><strong>Equipment:</strong> {$eqData['equipment_name']}<br>
                           <strong>Requested By:</strong> {$userData['full_name']}<br>
                           <strong>Department:</strong> {$deptData['name']}<br>
                           <strong>Urgency:</strong> $urgency<br>
                           <strong>Description:</strong> $descSafe</p>
                        <p>Please take necessary action.</p>
                    </div>";
                sendEmail($hod['email'], $hod['full_name'], $subjectHod, $htmlHod, "New maintenance request submitted.");
            }

            mysqli_stmt_close($stmt);
            header("Location: ../maintenance.php?msg=report_success");
            exit();

        } else {
            $errors[] = "Failed to submit report. Please try again.";
        }
    }
}
?>