<?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 CHECK
===================================== */
if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'hod') {

    echo json_encode([
        'status' => 'error',
        'message' => 'Unauthorized'
    ]);

    exit;
}

$hod_id = $_SESSION['user_id'];

/* =====================================
   EMAIL FUNCTION
===================================== */
function sendEmail($toEmail, $toName, $subject, $htmlBody)
{
    $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;

        // IMPORTANT
        $mail->SMTPDebug = 0;

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

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

        $mail->addAddress($toEmail, $toName);

        $mail->isHTML(true);

        $mail->Subject = $subject;
        $mail->Body    = $htmlBody;

        return $mail->send();

    } catch (Exception $e) {

        error_log("MAIL ERROR: " . $mail->ErrorInfo);

        return false;
    }
}

/* =====================================
   GET POST DATA
===================================== */
$request_id       = intval($_POST['request_id'] ?? 0);
$technician_id    = intval($_POST['technician_id'] ?? 0);
$maintenance_date = trim($_POST['maintenance_date'] ?? '');

if (
    $request_id <= 0 ||
    $technician_id <= 0 ||
    empty($maintenance_date)
) {

    echo json_encode([
        'status' => 'error',
        'message' => 'Please complete all fields'
    ]);

    exit;
}

/* =====================================
   GET REQUEST + USER + EQUIPMENT
===================================== */
$sql = "
SELECT
    mr.*,
    u.full_name AS requester_name,
    u.email AS requester_email,
    e.equipment_name,
    e.status AS equipment_status
FROM maintenance_request mr
JOIN users u ON mr.requested_by = u.id
JOIN equipment e ON mr.equipment_id = e.id
WHERE mr.id = ?
LIMIT 1
";

$stmt = mysqli_prepare($conn, $sql);

mysqli_stmt_bind_param($stmt, "i", $request_id);

mysqli_stmt_execute($stmt);

$res = mysqli_stmt_get_result($stmt);

$request = mysqli_fetch_assoc($res);

if (!$request) {

    echo json_encode([
        'status' => 'error',
        'message' => 'Request not found'
    ]);

    exit;
}

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

mysqli_stmt_bind_param(
    $techStmt,
    "i",
    $technician_id
);

mysqli_stmt_execute($techStmt);

$techRes = mysqli_stmt_get_result($techStmt);

$technician = mysqli_fetch_assoc($techRes);

if (!$technician) {

    echo json_encode([
        'status' => 'error',
        'message' => 'Technician not found'
    ]);

    exit;
}

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

mysqli_stmt_bind_param(
    $hodStmt,
    "i",
    $hod_id
);

mysqli_stmt_execute($hodStmt);

$hodRes = mysqli_stmt_get_result($hodStmt);

$hod = mysqli_fetch_assoc($hodRes);

/* =====================================
   INSERT MAINTENANCE RECORD
===================================== */
$insert = mysqli_prepare($conn,
"
INSERT INTO maintenance_record
(
    equipment_id,
    request_id,
    technician_id,
    description,
    maintenance_date,
    status
)
VALUES
(
    ?,
    ?,
    ?,
    ?,
    ?,
    'In Progress'
)
");

mysqli_stmt_bind_param(
    $insert,
    "iiiss",
    $request['equipment_id'],
    $request_id,
    $technician_id,
    $request['issue_description'],
    $maintenance_date
);

if (!mysqli_stmt_execute($insert)) {

    echo json_encode([
        'status' => 'error',
        'message' => 'Failed to create maintenance record'
    ]);

    exit;
}

/* =====================================
   UPDATE REQUEST STATUS
===================================== */

$reviewed_at = date('Y-m-d H:i:s');

$updateReq = mysqli_prepare($conn,
"
UPDATE maintenance_request
SET
    status = 'Assigned',
    assigned_to = ?,
    reviewed_by = ?,
    reviewed_at = ?
WHERE id = ?
"
);

mysqli_stmt_bind_param(
    $updateReq,
    "iisi",
    $technician_id,
    $hod_id,
    $reviewed_at,
    $request_id
);

mysqli_stmt_execute($updateReq);

/* =====================================
   UPDATE EQUIPMENT STATUS
===================================== */
$updateEq = mysqli_prepare($conn,
"
UPDATE equipment
SET status='Under Maintenance'
WHERE id=?
");

mysqli_stmt_bind_param(
    $updateEq,
    "i",
    $request['equipment_id']
);

mysqli_stmt_execute($updateEq);

/* =====================================
   EMAIL TO REPORTER
===================================== */
$userSubject = "Maintenance Approved - QRCareTrack";

$userBody = "
<div style='font-family:Segoe UI,sans-serif;padding:20px;'>

<h2>Maintenance Request Approved</h2>

<p>Hi {$request['requester_name']},</p>

<p>
Your maintenance request has been approved.
</p>

<p>
<b>Equipment:</b> {$request['equipment_name']}<br>
<b>Assigned Technician:</b> {$technician['full_name']}<br>
<b>Maintenance Date:</b> {$maintenance_date}
</p>

<p>
Your equipment is now under maintenance.
</p>

</div>
";

sendEmail(
    $request['requester_email'],
    $request['requester_name'],
    $userSubject,
    $userBody
);

/* =====================================
   EMAIL TO TECHNICIAN
===================================== */
$techSubject = "New Maintenance Task Assigned";

$techBody = "
<div style='font-family:Segoe UI,sans-serif;padding:20px;'>

<h2>New Maintenance Task</h2>

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

<p>
You have been assigned a new maintenance task.
</p>

<p>
<b>Equipment:</b> {$request['equipment_name']}<br>
<b>Maintenance Date:</b> {$maintenance_date}
</p>

<p>
<b>Issue:</b><br>
{$request['issue_description']}
</p>

</div>
";

sendEmail(
    $technician['email'],
    $technician['full_name'],
    $techSubject,
    $techBody
);

/* =====================================
   EMAIL TO HOD
===================================== */
$hodSubject = "Maintenance Assignment Successful";

$hodBody = "
<div style='font-family:Segoe UI,sans-serif;padding:20px;'>

<h2>Maintenance Assigned Successfully</h2>

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

<p>
You have successfully assigned:
</p>

<p>
<b>Technician:</b> {$technician['full_name']}<br>
<b>Equipment:</b> {$request['equipment_name']}<br>
<b>Maintenance Date:</b> {$maintenance_date}
</p>

</div>
";

sendEmail(
    $hod['email'],
    $hod['full_name'],
    $hodSubject,
    $hodBody
);

/* =====================================
   SUCCESS
===================================== */

$_SESSION['success_message'] = "Technician assigned successfully";

header("Location: ../maintenance.php");
exit;
?>