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

require_once "../config/db.php";
require_once "../inc/auth_admin.php";

/* =========================
   FILTER + SEARCH
========================= */
$filter = $_GET['status'] ?? 'semua';
$search = $_GET['search'] ?? '';

/* =========================
   TAMBAH PENGHUNI
========================= */
if (isset($_POST['tambah_penghuni'])) {

    $nama = $_POST['nama'];
    $no_hp = $_POST['no_hp'];
    $ktp = $_POST['ktp'];
    $kamar_id = intval($_POST['kamar_id']);
    $tanggal_masuk = date('Y-m-d');

    /* CEK KAMAR TERISI */
    $cek = $conn->prepare("SELECT status FROM kamar WHERE id=?");
    $cek->bind_param("i",$kamar_id);
    $cek->execute();
    $res = $cek->get_result()->fetch_assoc();

    if($res['status']=='terisi'){
        die("Kamar sudah terisi");
    }

    $password_hash = password_hash($no_hp, PASSWORD_DEFAULT);

    $stmt = $conn->prepare("
        INSERT INTO penghuni 
        (nama,no_hp,ktp,kamar_id,tanggal_masuk,status,password) 
        VALUES (?, ?, ?, ?, ?, 'aktif', ?)
    ");

    $stmt->bind_param("ssssis", $nama,$no_hp,$ktp,$kamar_id,$tanggal_masuk,$password_hash);
    $stmt->execute();
    /* simpan riwayat kamar */
$stmt3 = $conn->prepare("
INSERT INTO riwayat_kamar 
(penghuni_id,kamar_id,tanggal_masuk) 
VALUES (?,?,?)
");

$penghuni_id = $conn->insert_id;

$stmt3->bind_param("iis",$penghuni_id,$kamar_id,$tanggal_masuk);
$stmt3->execute();

    $stmt2 = $conn->prepare("UPDATE kamar SET status='terisi' WHERE id=?");
    $stmt2->bind_param("i", $kamar_id);
    $stmt2->execute();

    header("Location: penghuni.php");
    exit;
}

/* =========================
   PENGHUNI KELUAR
========================= */
if (isset($_GET['keluar'])) {

    $id = intval($_GET['keluar']);
    $data = $conn->query("SELECT kamar_id FROM penghuni WHERE id=$id")->fetch_assoc();
    $kamar_id = $data['kamar_id'];
    $today = date('Y-m-d');

    $stmt = $conn->prepare("UPDATE penghuni SET status='nonaktif', tanggal_keluar=? WHERE id=?");
    $stmt->bind_param("si", $today, $id);
    $stmt->execute();

    $stmt2 = $conn->prepare("UPDATE kamar SET status='kosong' WHERE id=?");
    $stmt2->bind_param("i", $kamar_id);
    $stmt2->execute();

    header("Location: penghuni.php?status=nonaktif");
    exit;
}

/* =========================
   RESET PASSWORD
========================= */
if (isset($_GET['reset'])) {

    $id = intval($_GET['reset']);
    $new_pass_plain = rand(100000,999999);
    $new_pass_hash  = password_hash($new_pass_plain, PASSWORD_DEFAULT);

    $stmt = $conn->prepare("UPDATE penghuni SET password=? WHERE id=?");
    $stmt->bind_param("si", $new_pass_hash, $id);
    $stmt->execute();

    header("Location: penghuni.php?status=$filter&reset_success=1&pass=$new_pass_plain");
    exit;
}

/* =========================
   FILTER QUERY
========================= */

$where = [];

if ($filter == 'aktif') {
    $where[] = "penghuni.status='aktif'";
} elseif ($filter == 'nonaktif') {
    $where[] = "penghuni.status='nonaktif'";
}

if(!empty($search)){
    $search_safe = $conn->real_escape_string($search);
    $where[] = "(penghuni.nama LIKE '%$search_safe%' 
                OR penghuni.no_hp LIKE '%$search_safe%' 
                OR kamar.nomor_kamar LIKE '%$search_safe%')";
}

$where_sql = "";
if(count($where)>0){
    $where_sql = "WHERE ".implode(" AND ",$where);
}

/* =========================
   AMBIL DATA
========================= */

$penghuni = $conn->query("
    SELECT penghuni.*, kamar.nomor_kamar 
    FROM penghuni
    JOIN kamar ON penghuni.kamar_id = kamar.id
    $where_sql
    ORDER BY penghuni.tanggal_masuk DESC
");

$kamar_kosong = $conn->query("SELECT * FROM kamar WHERE status='kosong'");
?>

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../assets/style.css">
<title>Data Penghuni - LuminaCare</title>

<style>
.page-title{
padding:30px 30px 10px 30px;
}

.page-title h1{
margin:0;
font-size:32px;
font-weight:700;
background:linear-gradient(90deg,#1e3a8a,#2563eb);
-webkit-background-clip:text;
color:transparent;
}

.page-title p{
margin-top:5px;
color:#6b7280;
font-size:14px;
}

/* garis dekorasi */
.page-title::after{
content:"";
display:block;
width:60px;
height:4px;
background:#2563eb;
border-radius:2px;
margin-top:10px;
}
body { margin:0; font-family:Arial; background:#f4f6f9; }

.header {
background:#1e3a8a;
color:white;
padding:20px;
display:flex;
justify-content:space-between;
}

.nav a {
color:white;
margin-left:20px;
text-decoration:none;
}

.container { padding:30px; }

.section {
background:white;
padding:20px;
border-radius:8px;
margin-bottom:30px;
box-shadow:0 4px 10px rgba(0,0,0,0.05);
}

input, select {
padding:8px;
margin-right:10px;
margin-bottom:10px;
}

button {
padding:8px 15px;
background:#2563eb;
color:white;
border:none;
border-radius:5px;
cursor:pointer;
}

.table-wrapper {
max-height:500px;
overflow-y:auto;
border-radius:8px;
}

table {
width:100%;
border-collapse:collapse;
background:white;
}

th, td {
padding:12px;
border-bottom:1px solid #ddd;
}

th {
background:#f1f5f9;
text-align:center;
}

.aktif { color:#16a34a; font-weight:bold; }
.nonaktif { color:#dc2626; font-weight:bold; }

.btn-reset { background:#f59e0b; }
.btn-keluar { background:#dc2626; }

.btn-reset,
.btn-keluar {
padding:6px 12px;
border-radius:4px;
color:white;
text-decoration:none;
font-size:13px;
margin-right:6px;
}

.filter a {
margin-right:15px;
text-decoration:none;
font-weight:bold;
}
</style>
</head>

<body>

<?php include "../inc/navbar_admin.php"; ?>
<div class="page-title">
    <h1>Data Penghuni</h1>
    <p>Monitoring Data Penghuni kost LuminaCare</p>
</div>
<div class="nav">

</div>
</div>

<div class="container">

<div class="section">
<h3>Tambah Penghuni</h3>

<form method="POST">
<input type="text" name="nama" placeholder="Nama Penghuni" required>
<input type="text" name="no_hp" placeholder="No HP" required>
<input type="text" name="ktp" placeholder="No KTP" required>

<select name="kamar_id" required>
<option value="">Pilih Kamar Kosong</option>
<?php while($k = $kamar_kosong->fetch_assoc()): ?>
<option value="<?= $k['id'] ?>">
<?= $k['nomor_kamar'] ?>
</option>
<?php endwhile; ?>
</select>

<button type="submit" name="tambah_penghuni">Tambah</button>
</form>

</div>

<div class="filter">
<a href="penghuni.php?status=semua">Semua</a>
<a href="penghuni.php?status=aktif">Aktif</a>
<a href="penghuni.php?status=nonaktif">Nonaktif</a>
</div>

<br>

<form method="GET">
<input type="hidden" name="status" value="<?= $filter ?>">
<input type="text" name="search" placeholder="Cari nama / HP / kamar" value="<?= htmlspecialchars($search) ?>">
<button type="submit">Cari</button>
</form>

<br>

<div class="table-wrapper">

<table>

<thead>
<tr>
<th>Nama</th>
<th>No HP</th>
<th>KTP</th>
<th>Kamar</th>
<th>Tgl Masuk</th>
<th>Tgl Keluar</th>
<th>Status</th>
<th>Aksi</th>
</tr>
</thead>

<tbody>

<?php while($row = $penghuni->fetch_assoc()): ?>

<tr>

<td><?= $row['nama'] ?></td>
<td><?= $row['no_hp'] ?></td>
<td><?= $row['ktp'] ?></td>
<td><?= $row['nomor_kamar'] ?></td>

<td><?= !empty($row['tanggal_masuk']) ? date('d-m-Y', strtotime($row['tanggal_masuk'])) : '-' ?></td>
<td><?= !empty($row['tanggal_keluar']) ? date('d-m-Y', strtotime($row['tanggal_keluar'])) : '-' ?></td>

<td class="<?= $row['status'] ?>">
<?= ucfirst($row['status']) ?>
</td>

<td>

<td>

<a href="edit_penghuni.php?id=<?= $row['id'] ?>"
style="background:#2563eb;padding:6px 12px;border-radius:4px;color:white;text-decoration:none;font-size:13px;margin-right:6px;">
Edit
</a>

<?php if($row['status']=='aktif'): ?>

<a href="penghuni.php?reset=<?= $row['id'] ?>&status=<?= $filter ?>" class="btn-reset">Reset</a>

<a href="penghuni.php?keluar=<?= $row['id'] ?>" 
class="btn-keluar"
onclick="return confirm('Yakin penghuni ini keluar dari kamar?')">
Keluar
</a>

<?php endif; ?>

</td>
</tr>

<?php endwhile; ?>

</tbody>

</table>

</div>

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

</body>
</html>