<?php
session_start();
require_once __DIR__ . "/../config/db.php";
require_once __DIR__ . "/../config/app.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'] != "technician") {
    header("Location: " . BASE_URL . "login.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$equipment_id = intval($_GET['id'] ?? 0);

if ($equipment_id <= 0) {
    die("Invalid equipment ID.");
}

$errors = [];
$message = "";

/* =========================================
   GET EQUIPMENT DETAILS
========================================= */
$stmt = mysqli_prepare($conn, "
    SELECT *
    FROM equipment
    WHERE id = ?
");

mysqli_stmt_bind_param($stmt, "i", $equipment_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$equipment = mysqli_fetch_assoc($result);

if (!$equipment) {
    die("Equipment not found.");
}

/* =========================================
   EMAIL FUNCTION
========================================= */
function sendEmail($toEmail, $toName, $subject, $htmlBody, $altBody = "")
{
    $mail = new PHPMailer(true);

    try {
        $mail->isSMTP();
        $mail->Host       = 'smtp.gmail.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'your_email@gmail.com';
        $mail->Password   = 'your_app_password';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = 587;

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

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

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

        return $mail->send();

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

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

    $service_type = trim($_POST['service_type'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $urgency = intval($_POST['urgency'] ?? 5);

    if ($service_type == "") {
        $errors[] = "Please select service type.";
    }

    if ($description == "") {
        $errors[] = "Please enter service description.";
    }

    if ($urgency < 1 || $urgency > 10) {
        $errors[] = "Invalid urgency selected.";
    }

    if (empty($errors)) {

        $full_description = $service_type . " - " . $description;

        /* =========================================
           INSERT REQUEST (WAITING HOD APPROVAL)
        ========================================= */
        $insert = mysqli_prepare($conn, "
            INSERT INTO maintenance_request
            (
                equipment_id,
                requested_by,
                issue_description,
                status,
                created_at,
                urgency
            )
            VALUES
            (?, ?, ?, 'Reported', NOW(), ?)
        ");

        mysqli_stmt_bind_param(
            $insert,
            "iisi",
            $equipment_id,
            $user_id,
            $full_description,
            $urgency
        );

        if (mysqli_stmt_execute($insert)) {

            /* =========================================
               FETCH USER INFO
            ========================================= */
            $userQ = mysqli_query($conn, "
                SELECT full_name, email
                FROM users
                WHERE id = $user_id
            ");

            $userData = mysqli_fetch_assoc($userQ);

            /* =========================================
               EMAIL TO TECHNICIAN
            ========================================= */
            $subjectUser = "Service 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>Service Request Submitted</h2>
                    <p>Hi {$userData['full_name']},</p>

                    <p>Your service request for 
                    <strong>{$equipment['equipment_name']}</strong> 
                    has been submitted successfully.</p>

                    <p>
                        <strong>Service Type:</strong> {$service_type}<br>
                        <strong>Urgency:</strong> {$urgency}<br>
                        <strong>Description:</strong> " . htmlspecialchars($description) . "
                    </p>

                    <p>Please wait for HOD approval before maintenance begins.</p>
                </div>
            ";

            sendEmail(
                $userData['email'],
                $userData['full_name'],
                $subjectUser,
                $htmlUser
            );

            /* =========================================
               EMAIL TO HOD
            ========================================= */
            $department_id = intval($equipment['department_id']);

            if ($department_id > 0) {

                $hodStmt = mysqli_prepare($conn, "
                    SELECT full_name, email
                    FROM users
                    WHERE role = 'hod'
                    AND department_id = ?
                ");

                mysqli_stmt_bind_param($hodStmt, "i", $department_id);
                mysqli_stmt_execute($hodStmt);
                $hodResult = mysqli_stmt_get_result($hodStmt);

                while ($hodData = mysqli_fetch_assoc($hodResult)) {

                    $subjectHod = "New Service Request Requires Approval - 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 Service Request</h2>

                            <p>Hi {$hodData['full_name']},</p>

                            <p>
                                A technician has submitted a preventive maintenance
                                request for equipment:
                                <strong>{$equipment['equipment_name']}</strong>
                            </p>

                            <p>
                                <strong>Requested By:</strong> {$userData['full_name']}<br>
                                <strong>Service Type:</strong> {$service_type}<br>
                                <strong>Urgency:</strong> {$urgency}<br>
                                <strong>Description:</strong> " . htmlspecialchars($description) . "
                            </p>

                            <p>Please review and approve/reject this request.</p>
                        </div>
                    ";

                    sendEmail(
                        $hodData['email'],
                        $hodData['full_name'],
                        $subjectHod,
                        $htmlHod
                    );
                }
            }

            header("Location: ../equipment/equipment_details.php?id=" . $equipment_id . "&service=request_submitted");
            exit();

        } else {
            $errors[] = "Failed to submit service request.";
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Request Preventive Maintenance</title>

    <link rel="stylesheet" href="<?= BASE_URL ?>assets/style.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">

    <style>
        .service-card {
            max-width: 850px;
            margin: 30px auto;
            background: #fff;
            padding: 35px;
            border-radius: 14px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.08);
        }

        .form-group {
            margin-top: 20px;
        }

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

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

        textarea {
            resize: vertical;
        }

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

        .btn-submit {
            background: #2563eb;
            color: white;
        }

        .btn-back {
            background: #e5e7eb;
            color: #111;
            margin-left: 10px;
        }

        .error {
            background: #fee2e2;
            color: #b91c1c;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>

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

<div class="main">

    <div class="service-card">

        <h2>
            <i class="fas fa-screwdriver-wrench"></i>
            Request Preventive Maintenance
        </h2>

        <?php if (!empty($errors)): ?>
            <div class="error">
                <?php foreach ($errors as $err): ?>
                    <?= htmlspecialchars($err) ?><br>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <p><strong>Equipment:</strong> <?= htmlspecialchars($equipment['equipment_name']) ?></p>
        <p><strong>Category:</strong> <?= htmlspecialchars($equipment['category']) ?></p>
        <p><strong>Serial Number:</strong> <?= htmlspecialchars($equipment['serial_number']) ?></p>
        <p><strong>Current Status:</strong> <?= htmlspecialchars($equipment['status']) ?></p>

        <form method="POST">

            <div class="form-group">
                <label>Service Type</label>
                <select name="service_type" required>
                    <option value="">-- Select Service Type --</option>
                    <option value="Preventive Maintenance">Preventive Maintenance</option>
                    <option value="Routine Inspection">Routine Inspection</option>
                    <option value="Calibration">Calibration</option>
                    <option value="Cleaning">Cleaning</option>
                </select>
            </div>

            <div class="form-group">
                <label>Urgency (1 = Low, 10 = High)</label>
                <input
                    type="range"
                    name="urgency"
                    min="1"
                    max="10"
                    value="5"
                >
            </div>

            <div class="form-group">
                <label>Description</label>
                <textarea
                    name="description"
                    rows="5"
                    placeholder="Describe what maintenance is needed..."
                    required
                ></textarea>
            </div>

            <button
                type="submit"
                class="btn btn-submit"
            >
                Submit Service Request
            </button>

            <a
                href="../equipment/equipment_details.php?id=<?= $equipment_id ?>"
                class="btn btn-back"
            >
                Back
            </a>

        </form>

    </div>

</div>

</body>
</html>