<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . "/../config/db.php";
require_once __DIR__ . "/../inc/auth_penghuni.php";

$id_penghuni = $_SESSION['penghuni_id'];

/* =========================
   AMBIL DATA KAMAR
========================= */
$stmtUser = $conn->prepare("SELECT kamar_id FROM penghuni WHERE id=?");
$stmtUser->bind_param("i", $id_penghuni);
$stmtUser->execute();
$stmtUser->bind_result($kamar_id);
$stmtUser->fetch();
$stmtUser->close();

/* Ambil nomor kamar */
$stmtKamar = $conn->prepare("SELECT nomor_kamar FROM kamar WHERE id=?");
$stmtKamar->bind_param("i", $kamar_id);
$stmtKamar->execute();
$stmtKamar->bind_result($nomor_kamar);
$stmtKamar->fetch();
$stmtKamar->close();

$error = "";

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

    $kategori  = trim($_POST['kategori']);
    $deskripsi = trim($_POST['deskripsi']);
    $tanggal   = date("Y-m-d");

    if (empty($kategori) || empty($deskripsi)) {
        $error = "Kategori dan deskripsi wajib diisi!";
    }

    $fotoNames   = [];
    $attachments = [];
    $target_dir  = __DIR__ . "/../uploads/";

    if (!is_dir($target_dir)) {
        mkdir($target_dir, 0755, true);
    }

    /* =========================
       UPLOAD MAX 4 FOTO
    ========================= */
    if (!$error && isset($_FILES['foto'])) {

        $total = count($_FILES['foto']['name']);

        for ($i=0; $i<$total && $i<4; $i++) {

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

                $ext = strtolower(pathinfo($_FILES["foto"]["name"][$i], PATHINFO_EXTENSION));
                $allowed = ['jpg','jpeg','png'];

                if (!in_array($ext, $allowed)) {
                    $error = "Format foto harus JPG/PNG!";
                    break;
                }

                $newName = "laporan_" . time() . "_$i.jpg";
                $target_file = $target_dir . $newName;

                list($width, $height) = getimagesize($_FILES['foto']['tmp_name'][$i]);

                $max_width = 1200;

                if ($width > $max_width) {
                    $new_width  = $max_width;
                    $new_height = floor($height * ($max_width / $width));
                } else {
                    $new_width  = $width;
                    $new_height = $height;
                }

                $new_image = imagecreatetruecolor($new_width, $new_height);

                if ($ext == 'png') {
                    $source = imagecreatefrompng($_FILES['foto']['tmp_name'][$i]);
                } else {
                    $source = imagecreatefromjpeg($_FILES['foto']['tmp_name'][$i]);
                }

                imagecopyresampled(
                    $new_image,
                    $source,
                    0,0,0,0,
                    $new_width,$new_height,
                    $width,$height
                );

                imagejpeg($new_image, $target_file, 75);

                imagedestroy($source);
                imagedestroy($new_image);

                $fotoNames[]   = $newName;
                $attachments[] = $target_file;
            }
        }
    }

    if (!$error) {

        $foto_string = implode(",", $fotoNames);

        $stmt = $conn->prepare("
            INSERT INTO laporan 
            (kamar_id, penghuni_id, kategori, deskripsi, foto, status, tanggal_lapor) 
            VALUES (?, ?, ?, ?, ?, 'baru', ?)
        ");

        $stmt->bind_param(
            "iissss",
            $kamar_id,
            $id_penghuni,
            $kategori,
            $deskripsi,
            $foto_string,
            $tanggal
        );

        if ($stmt->execute()) {

            require_once "../inc/mailer.php";

            $random   = rand(100,999);
            $datePart = date("md");
            $ticket   = "LC-$nomor_kamar-$datePart-$random";

            $subject = "[$ticket] $kategori - Kamar $nomor_kamar | LuminaCare";

            $body = "
            <h2>Laporan Baru Masuk</h2>
            <p><b>Ticket:</b> $ticket</p>
            <p><b>Kamar:</b> $nomor_kamar</p>
            <p><b>Kategori:</b> $kategori</p>
            <p><b>Deskripsi:</b> $deskripsi</p>
            <p><b>Tanggal:</b> $tanggal</p>
            ";

            $admin_emails = [
                "mramli520@gmail.com",
                "dian.febrima@sinesa.id",
                "ddfebrima1@gmail.com",
                "support@laporan.my.id"
            ];

            foreach ($admin_emails as $email) {
                kirimEmail($email, $subject, $body, $attachments);
            }

            header("Location: dashboard.php");
            exit;

        } else {
            $error = "Gagal menyimpan laporan!";
        }

        $stmt->close();
    }
}
?>

<!DOCTYPE html>
<html>
<head>

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../assets/style.css">

<title>Buat Laporan - LuminaCare</title>

<style>

.header{
background:#16a34a;
color:white;
padding:20px;
display:flex;
justify-content:space-between;
align-items:center;
}

.container{
max-width:600px;
margin:40px auto;
background:white;
padding:30px;
border-radius:12px;
box-shadow:0 5px 20px rgba(0,0,0,0.1);
}

input, textarea, select{
width:100%;
padding:10px;
margin-bottom:15px;
border:1px solid #ddd;
border-radius:6px;
}

button{
background:#2563eb;
color:white;
padding:12px;
border:none;
border-radius:6px;
cursor:pointer;
}

button:hover{
opacity:0.9;
}

.error{
background:#dc2626;
color:white;
padding:10px;
border-radius:6px;
margin-bottom:15px;
}

/* tombol sama seperti dashboard */
.btn{
display:inline-block;
padding:10px 15px;
border-radius:5px;
text-decoration:none;
font-size:14px;
color:white;
}

.btn-primary{
background:#2563eb;
}

.btn-primary:hover{
opacity:0.85;
}

</style>

</head>

<body>

<div class="header">
<div><b>LuminaCare - Buat Laporan</b></div>
<div>Kamar <?= $nomor_kamar ?></div>
</div>

<div class="container">

<h2>Buat Laporan Kerusakan</h2>

<?php if($error): ?>
<div class="error"><?= $error ?></div>
<?php endif; ?>

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

<label>Kategori</label>

<select name="kategori" required>
<option value="">-- Pilih Kategori --</option>
<option>Listrik</option>
<option>Air</option>
<option>AC</option>
<option>Kunci / Pintu</option>
<option>Kamar Mandi</option>
<option>Lainnya</option>
</select>

<label>Deskripsi</label>
<textarea name="deskripsi" rows="4" required></textarea>

<label>Upload Foto (Max 4)</label>
<input type="file" name="foto[]" multiple accept="image/*">

<button type="submit">Kirim Laporan</button>

</form>

<br>

<a href="dashboard.php" class="btn btn-primary">
← Kembali ke Dashboard
</a>

</div>
<?php include "../inc/footer.php"; ?>

</body>
</html>
