<?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 = [];

/* =========================
   FILTER + SEARCH
========================= */

$search = $_GET['search'] ?? '';
$category_filter = $_GET['category'] ?? '';
$department_filter = $_GET['department'] ?? '';

$conditions = [];

if (!empty($search)) {

    $search_safe = mysqli_real_escape_string($conn, $search);

    $conditions[] = "
    (
        equipment_name LIKE '%$search_safe%'
        OR serial_number LIKE '%$search_safe%'
    )";
}

if (!empty($category_filter)) {

    $category_safe = mysqli_real_escape_string(
        $conn,
        $category_filter
    );

    $conditions[] = "category='$category_safe'";
}

if (!empty($department_filter)) {

    $department_safe = mysqli_real_escape_string(
        $conn,
        $department_filter
    );

    $conditions[] = "department='$department_safe'";
}

$where = !empty($conditions)
    ? "WHERE " . implode(" AND ", $conditions)
    : "";

/* =========================
   FETCH EQUIPMENT
========================= */

$equipments = [];

$equipQuery = "
SELECT *
FROM equipment
$where
ORDER BY equipment_name ASC
";

$equipResult = mysqli_query($conn, $equipQuery);

while ($eq = mysqli_fetch_assoc($equipResult)) {
    $equipments[] = $eq;
}

/* =========================
   DROPDOWN DATA
========================= */

$departmentResult = mysqli_query($conn, "
SELECT DISTINCT department
FROM equipment
WHERE department IS NOT NULL
ORDER BY department ASC
");

$categoryResult = mysqli_query($conn, "
SELECT DISTINCT category
FROM equipment
WHERE category IS NOT NULL
ORDER BY category ASC
");

/* =========================
   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   = 'hifzhanfatihin30@gmail.com';
        $mail->Password   = 'ntqx vlyx slsw kuos';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = 587;

        $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;
    }
}

/* =========================
   HANDLE FORM SUBMIT
========================= */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $equipment_id = intval($_POST['equipment_id'] ?? 0);

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

    $description = trim($_POST['issue_description'] ?? '');

    $issue_image = null;

    /* VALIDATION */

    if ($equipment_id <= 0) {
        $errors[] = "Please select equipment.";
    }

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

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

    /* IMAGE UPLOAD */

    if (!empty($_FILES['issue_image']['name'])) {

        $uploadDir = "../assets/report_images/";

        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        $ext = strtolower(
            pathinfo(
                $_FILES['issue_image']['name'],
                PATHINFO_EXTENSION
            )
        );

        $allowed = ['jpg', 'jpeg', 'png', 'webp'];

        if (!in_array($ext, $allowed)) {

            $errors[] = "Only JPG, JPEG, PNG & WEBP allowed.";

        } else {

            $issue_image =
                time() . "_" . rand(1000,9999) . "." . $ext;

            move_uploaded_file(
                $_FILES['issue_image']['tmp_name'],
                $uploadDir . $issue_image
            );
        }
    }

    /* SAVE DATABASE */

    if (empty($errors)) {

        $stmt = mysqli_prepare(
            $conn,
            "INSERT INTO maintenance_request
            (
                equipment_id,
                requested_by,
                issue_description,
                status,
                created_at,
                urgency,
                issue_image
            )
            VALUES
            (
                ?, ?, ?, 'Reported', NOW(), ?, ?
            )"
        );

        mysqli_stmt_bind_param(
            $stmt,
            "iisis",
            $equipment_id,
            $user_id,
            $description,
            $urgency,
            $issue_image
        );

        if (mysqli_stmt_execute($stmt)) {

            mysqli_stmt_close($stmt);

            /* FETCH USER */

            $userQ = mysqli_query(
                $conn,
                "SELECT full_name, email
                 FROM users
                 WHERE id = $user_id"
            );

            $userData = mysqli_fetch_assoc($userQ);

            /* FETCH EQUIPMENT */

            $eqStmt = mysqli_prepare(
                $conn,
                "SELECT equipment_name, department_id
                 FROM equipment
                 WHERE id=?"
            );

            mysqli_stmt_bind_param(
                $eqStmt,
                "i",
                $equipment_id
            );

            mysqli_stmt_execute($eqStmt);

            $eqResult = mysqli_stmt_get_result($eqStmt);

            $eqData = mysqli_fetch_assoc($eqResult);

            /* EMAIL USER */

            $subjectUser =
                "Maintenance Request Submitted - QRCareTrack";

            $htmlUser = "
            <div style='font-family:Segoe UI,sans-serif;'>

                <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>Urgency:</strong> $urgency
                    <br>
                    <strong>Description:</strong>
                    " . htmlspecialchars($description) . "
                </p>

            </div>";

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

            /* EMAIL HOD */

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

            if ($equipmentDepartment > 0) {

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

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

                mysqli_stmt_execute($hodStmt);

                $hodResult =
                    mysqli_stmt_get_result($hodStmt);

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

                    $subjectHod =
                        "New Maintenance Request - QRCareTrack";

                    $htmlHod = "
                    <div style='font-family:Segoe UI,sans-serif;'>

                        <h2>New Maintenance Request</h2>

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

                        <p>
                            A new issue has been reported for
                            <strong>{$eqData['equipment_name']}</strong>.
                        </p>

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

                    </div>";

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

            header(
                "Location: ../maintenance.php?msg=report_success"
            );

            exit();

        } else {

            $errors[] = "Failed to submit report.";

            error_log(mysqli_error($conn));
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>

<title>Report Issue - QRCareTrack</title>

<link rel="stylesheet" href="../assets/style.css">

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

<style>

body{
    background:#f3fdfc;
}

.main{
    margin-left:220px;
    padding:35px;
}

.page-header{
    margin-bottom:25px;
}

.page-header h1{
    color:#0f766e;
    margin-bottom:8px;
}

.page-header p{
    color:#64748b;
}

.filter-box{
    display:flex;
    gap:12px;
    flex-wrap:wrap;
    margin-bottom:30px;
    padding:20px;
    background:#ffffff;
    border:1px solid #d7f3ef;
    border-radius:20px;
}

.report-layout{
    display:grid;
    grid-template-columns:1.1fr 0.9fr;
    gap:25px;
}

.card{
    background:#ffffff;
    border-radius:22px;
    padding:30px;
    border:1px solid #d7f3ef;
}

.form-title{
    color:#0f766e;
    font-size:28px;
    margin-bottom:8px;
}

.form-subtitle{
    color:#64748b;
    margin-bottom:30px;
}

.form-group{
    margin-bottom:25px;
}

.form-group label{
    display:block;
    margin-bottom:10px;
    font-weight:700;
    color:#0f172a;
}

.form-control{
    width:100%;
    padding:15px;
    border-radius:14px;
    border:1px solid #d1d5db;
    font-size:15px;
}

.form-control:focus{
    outline:none;
    border-color:#14b8a6;
    box-shadow:0 0 0 4px rgba(20,184,166,0.15);
}

textarea.form-control{
    resize:vertical;
    min-height:140px;
}

.filter-btn{
    background:#0f766e;
    color:#fff;
    border:none;
    padding:14px 20px;
    border-radius:14px;
    font-weight:700;
    cursor:pointer;
}

.reset-btn{
    background:#64748b;
    color:#fff;
    padding:14px 20px;
    border-radius:14px;
    font-weight:700;
    text-decoration:none;
}

.upload-preview{
    margin-top:15px;
}

.upload-preview img{
    width:100%;
    max-width:220px;
    border-radius:16px;
    border:3px solid #ccfbf1;
}

.range-wrap{
    margin-top:10px;
}

.range-value{
    margin-top:10px;
    font-size:18px;
    font-weight:700;
    color:#0f766e;
}

input[type=range]{
    width:100%;
}

.submit-btn{
    width:100%;
    border:none;
    background:#0f766e;
    color:#fff;
    padding:16px;
    border-radius:14px;
    font-size:16px;
    font-weight:700;
    cursor:pointer;
}

.submit-btn:hover{
    background:#115e59;
}

.equipment-image-wrapper{
    text-align:center;
    margin-bottom:20px;
}

.equipment-preview-image{
    width:100%;
    max-width:180px;
    height:180px;
    object-fit:cover;
    border-radius:20px;
    border:4px solid #d1fae5;
}

.info-title{
    margin-bottom:20px;
    color:#0f766e;
    font-size:22px;
}

.info-list{
    display:flex;
    flex-direction:column;
    gap:15px;
}

.info-item{
    background:#f8fffe;
    border:1px solid #dff7f3;
    border-radius:14px;
    padding:14px 16px;
}

.info-label{
    display:block;
    font-size:12px;
    color:#64748b;
    margin-bottom:6px;
    font-weight:700;
    text-transform:uppercase;
}

.info-value{
    font-size:16px;
    font-weight:700;
    color:#0f172a;
}

.error-box{
    background:#fee2e2;
    color:#b91c1c;
    padding:15px;
    border-radius:12px;
    margin-bottom:20px;
}

@media(max-width:900px){

    .main{
        margin-left:0;
        padding:20px;
    }

    .report-layout{
        grid-template-columns:1fr;
    }

}

</style>

</head>

<body>

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

<div class="main">

<div class="page-header">

    <h1>Report Equipment Issue</h1>

    <p>
        Submit maintenance issue reports quickly.
    </p>

</div>

<!-- FILTER BAR -->

<form method="GET" class="filter-box">

    <input
    type="text"
    name="search"
    placeholder="Search equipment or serial..."
    value="<?= htmlspecialchars($search) ?>"
    class="form-control"
    style="flex:1; min-width:220px;"
    >

    <select
    name="category"
    class="form-control"
    style="max-width:220px;"
    >

        <option value="">
            All Category
        </option>

        <?php while($cat = mysqli_fetch_assoc($categoryResult)): ?>

        <option
        value="<?= htmlspecialchars($cat['category']) ?>"
        <?=($category_filter == $cat['category']) ? 'selected' : ''?>
        >

        <?= htmlspecialchars($cat['category']) ?>

        </option>

        <?php endwhile; ?>

    </select>

    <select
    name="department"
    class="form-control"
    style="max-width:220px;"
    >

        <option value="">
            All Department
        </option>

        <?php while($dept = mysqli_fetch_assoc($departmentResult)): ?>

        <option
        value="<?= htmlspecialchars($dept['department']) ?>"
        <?=($department_filter == $dept['department']) ? 'selected' : ''?>
        >

        <?= htmlspecialchars($dept['department']) ?>

        </option>

        <?php endwhile; ?>

    </select>

    <button type="submit" class="filter-btn">

        <i class="fa-solid fa-filter"></i>
        Filter

    </button>

    <a href="report_issue.php" class="reset-btn">
        Reset
    </a>

</form>

<div class="report-layout">

    <!-- LEFT -->

    <div class="card">

        <h2 class="form-title">
            Maintenance Report
        </h2>

        <p class="form-subtitle">
            Fill in the equipment issue details below.
        </p>

        <?php if(!empty($errors)): ?>

            <div class="error-box">

                <?php foreach($errors as $err): ?>

                    <?= htmlspecialchars($err) ?><br>

                <?php endforeach; ?>

            </div>

        <?php endif; ?>

        <form method="POST" enctype="multipart/form-data">

            <div class="form-group">

                <label>Select Equipment</label>

                <select
                    name="equipment_id"
                    id="equipment_id"
                    class="form-control"
                    required
                >

                    <option value="">
                        Choose Equipment
                    </option>

                    <?php foreach($equipments as $eq):

                        $json = htmlspecialchars(json_encode([

                            'category'=>$eq['category'],
                            'purchase_date'=>$eq['purchase_date'],
                            'next_due_date'=>$eq['next_due_date'],
                            'description'=>$eq['description'],
                            'serial_number'=>$eq['serial_number'],
                            'location'=>$eq['location'],
                            'status'=>$eq['status'],
                            'department'=>$eq['department'],
                            'image'=>!empty($eq['image'])
                                ? "../assets/images/".$eq['image']
                                : "../assets/images/placeholder.png"

                        ]), ENT_QUOTES, 'UTF-8');

                    ?>

                    <option
                        value="<?= $eq['id'] ?>"
                        data-info='<?= $json ?>'
                    >

                        <?= htmlspecialchars($eq['equipment_name']) ?>

                    </option>

                    <?php endforeach; ?>

                </select>

            </div>

            <div class="form-group">

                <label>Urgency Level</label>

                <div class="range-wrap">

                    <input
                        type="range"
                        name="urgency"
                        id="urgency"
                        min="1"
                        max="10"
                        value="5"
                        oninput="updateUrgency(this.value)"
                    >

                    <div class="range-value">

                        Level:
                        <span id="urgencyValue">5</span>

                    </div>

                </div>

            </div>

            <div class="form-group">

                <label>Issue Description</label>

                <textarea
                    name="issue_description"
                    class="form-control"
                    placeholder="Describe the issue..."
                    required
                ></textarea>

            </div>

            <div class="form-group">

                <label>Upload Issue Image</label>

                <input
                    type="file"
                    name="issue_image"
                    accept=".jpg,.jpeg,.png,.webp"
                    class="form-control"
                    onchange="previewImage(event)"
                >

                <div class="upload-preview">

                    <img
                        id="preview"
                        src="../assets/images/placeholder.png"
                    >

                </div>

            </div>

            <button type="submit" class="submit-btn">
                Submit Maintenance Report
            </button>

        </form>

    </div>

    <!-- RIGHT -->

    <div class="card">

        <div class="equipment-image-wrapper">

            <img
                id="details-preview"
                src="../assets/images/placeholder.png"
                class="equipment-preview-image"
            >

        </div>

        <h3 class="info-title">
            Equipment Information
        </h3>

        <div class="info-list">

            <div class="info-item">
                <span class="info-label">Category</span>
                <span class="info-value" id="detail-category">-</span>
            </div>

            <div class="info-item">
                <span class="info-label">Serial Number</span>
                <span class="info-value" id="detail-serial">-</span>
            </div>

            <div class="info-item">
                <span class="info-label">Department</span>
                <span class="info-value" id="detail-dept">-</span>
            </div>

            <div class="info-item">
                <span class="info-label">Status</span>
                <span class="info-value" id="detail-status">-</span>
            </div>

            <div class="info-item">
                <span class="info-label">Location</span>
                <span class="info-value" id="detail-location">-</span>
            </div>

            <div class="info-item">
                <span class="info-label">Purchase Date</span>
                <span class="info-value" id="detail-purchase">-</span>
            </div>

            <div class="info-item">
                <span class="info-label">Next Due Date</span>
                <span class="info-value" id="detail-nextdue">-</span>
            </div>

        </div>

    </div>

</div>

</div>

<script>

const equipmentSelect = document.getElementById('equipment_id');

equipmentSelect.addEventListener('change', function(){

    const selected = this.options[this.selectedIndex];

    const info = JSON.parse(
        selected.getAttribute('data-info')
    );

    document.getElementById('details-preview').src =
        info.image;

    document.getElementById('detail-category').innerText =
        info.category || '-';

    document.getElementById('detail-serial').innerText =
        info.serial_number || '-';

    document.getElementById('detail-dept').innerText =
        info.department || '-';

    document.getElementById('detail-status').innerText =
        info.status || '-';

    document.getElementById('detail-location').innerText =
        info.location || '-';

    document.getElementById('detail-purchase').innerText =
        info.purchase_date || '-';

    document.getElementById('detail-nextdue').innerText =
        info.next_due_date || '-';

});

function previewImage(event){

    const reader = new FileReader();

    reader.onload = function(){

        document.getElementById('preview').src =
            reader.result;

    }

    reader.readAsDataURL(event.target.files[0]);

}

function updateUrgency(val){

    document.getElementById('urgencyValue').innerText = val;

}

</script>

</body>
</html>