<?php
require_once __DIR__ . "/../config/db.php";

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

require_once __DIR__ . "/../vendor/PHPMailer/src/Exception.php";
require_once __DIR__ . "/../vendor/PHPMailer/src/PHPMailer.php";
require_once __DIR__ . "/../vendor/PHPMailer/src/SMTP.php";

/* =========================================
   EMAIL FUNCTION (same as report_issue.php)
========================================= */
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';
        $mail->Password   = 'ntqx vlyx slsw kuos';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = 587;

        // Fix SSL issue (XAMPP)
        $mail->SMTPOptions = [
            'ssl' => [
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            ]
        ];

        $mail->setFrom('hifzhanfatihin30@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;
    }
}

/* =========================================
   SEND SERVICE NOTIFICATION
   (After HOD Approval)
========================================= */
function sendServiceNotification($equipment_id, $requested_by, $description = "")
{
    global $conn;

    /* ===============================
       GET EQUIPMENT DETAILS
    =============================== */
    $eqStmt = mysqli_prepare($conn, "
        SELECT equipment_name, department_id
        FROM equipment
        WHERE id = ?
        LIMIT 1
    ");

    mysqli_stmt_bind_param($eqStmt, "i", $equipment_id);
    mysqli_stmt_execute($eqStmt);
    $eqResult = mysqli_stmt_get_result($eqStmt);
    $eqData = mysqli_fetch_assoc($eqResult);

    if (!$eqData) {
        error_log("Equipment not found.");
        return false;
    }

    $equipment_name = $eqData['equipment_name'];
    $department_id  = intval($eqData['department_id']);

    if ($department_id <= 0) {
        error_log("Invalid department ID.");
        return false;
    }

    /* ===============================
       GET REQUESTER INFO
    =============================== */
    $userStmt = mysqli_prepare($conn, "
        SELECT full_name
        FROM users
        WHERE id = ?
        LIMIT 1
    ");

    mysqli_stmt_bind_param($userStmt, "i", $requested_by);
    mysqli_stmt_execute($userStmt);
    $userResult = mysqli_stmt_get_result($userStmt);
    $userData = mysqli_fetch_assoc($userResult);

    $requested_by_name = $userData['full_name'] ?? "System User";

    /* ===============================
       FIND ALL TECHNICIANS
       IN SAME DEPARTMENT
    =============================== */
    $techStmt = mysqli_prepare($conn, "
        SELECT full_name, email
        FROM users
        WHERE role = 'technician'
        AND department_id = ?
        AND email IS NOT NULL
        AND email != ''
    ");

    mysqli_stmt_bind_param($techStmt, "i", $department_id);
    mysqli_stmt_execute($techStmt);
    $techResult = mysqli_stmt_get_result($techStmt);

    if (mysqli_num_rows($techResult) <= 0) {
        error_log("No technicians found for department ID: " . $department_id);
        return false;
    }

    /* ===============================
       SEND EMAIL TO TECHNICIANS
    =============================== */
    while ($tech = mysqli_fetch_assoc($techResult)) {

        $subject = "New Service Request Approved - QRCareTrack";

        $htmlBody = "
            <div style='font-family:Segoe UI,sans-serif; max-width:600px; margin:auto; padding:20px; border:1px solid #ddd; border-radius:8px;'>

                <h2>Service Notification</h2>

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

                <p>
                    A service request has been approved for the following equipment:
                </p>

                <p>
                    <strong>Equipment:</strong> {$equipment_name}<br>
                    <strong>Requested By:</strong> {$requested_by_name}<br>
                    <strong>Description:</strong> " . htmlspecialchars($description) . "
                </p>

                <p>
                    Please proceed with the maintenance/service task.
                </p>

                <p>
                    Thank you,<br>
                    <strong>QRCareTrack System</strong>
                </p>

            </div>
        ";

        $altBody = "New approved service request for equipment: {$equipment_name}";

        if (sendEmail(
            $tech['email'],
            $tech['full_name'],
            $subject,
            $htmlBody,
            $altBody
        )) {
            error_log("Service notification sent to: " . $tech['email']);
        } else {
            error_log("Failed sending to: " . $tech['email']);
        }
    }

    return true;
}