<?php
require_once "../config.php";
require_once "../auth.php";
require_login();

include "header.php";

/* ========================= SweetAlert Helper ========================= */
function swal($title, $text, $icon, $redirect = null) {
    echo "<script>
        Swal.fire({
            title: '$title',
            text: '$text',
            icon: '$icon',
            confirmButtonText: 'ตกลง'
        }).then(() => {";

    if ($redirect) {
        echo "window.location='$redirect';";
    }

    echo "});
    </script>";
}

/* ==========================================================
   STAFF / ADMIN → เห็นทั้งหมด  
   USER → เห็นเฉพาะของตัวเอง
========================================================== */
if ($ROLE == "user") {
    $filter = "WHERE beacons.user_id = $USER_ID";
} else {
    $filter = "";
}

/* ==========================================================
   ADD BEACON (FIXED)
========================================================== */
if (isset($_POST['add_beacon'])) {

    $uuid  = trim($_POST['uuid']);
    $major = intval($_POST['major']);
    $minor = intval($_POST['minor']);
    $place = trim($_POST['place']);
    $notify = $_POST['notify_type'];

    if ($ROLE == "user") {
        $owner = $USER_ID;
    } else {
        $owner = intval($_POST['user_id']);
        staff_cannot_edit_admin($owner, $conn);
    }

    $stmt = $conn->prepare("
        INSERT INTO beacons (uuid, major, minor, location, user_id, notify_type)
        VALUES (?, ?, ?, ?, ?, ?)
    ");

    /* ✨ แก้ bind_param ให้ถูกต้อง */
    $stmt->bind_param("siisis", $uuid, $major, $minor, $place, $owner, $notify);

    if ($stmt->execute()) {
        swal("สำเร็จ", "เพิ่ม Beacon สำเร็จ", "success", "beacons.php");
    } else {
        swal("ผิดพลาด", "เพิ่มข้อมูลไม่สำเร็จ", "error", "beacons.php");
    }
}

/* ==========================================================
   EDIT BEACON (FIXED)
========================================================== */
if (isset($_POST['edit_beacon'])) {

    $id    = intval($_POST['beacon_id']);
    $uuid  = trim($_POST['uuid']);
    $major = intval($_POST['major']);
    $minor = intval($_POST['minor']);
    $place = trim($_POST['place']);
    $notify = $_POST['notify_type'];

    $q = $conn->query("SELECT user_id FROM beacons WHERE id=$id");
    $old = $q->fetch_assoc();

    if (!$old) {
        swal("ข้อผิดพลาด", "ไม่พบข้อมูล Beacon", "error", "beacons.php");
        exit;
    }

    if ($ROLE == "user" && $old['user_id'] != $USER_ID) {
        swal("สิทธิ์ไม่เพียงพอ", "คุณไม่มีสิทธิ์แก้ไข Beacon นี้", "error", "beacons.php");
        exit;
    }

    if ($ROLE == "user") {
        $owner = $old['user_id'];
    } else {
        $owner = intval($_POST['user_id']);
        staff_cannot_edit_admin($owner, $conn);
    }

    $stmt = $conn->prepare("
        UPDATE beacons 
        SET uuid=?, major=?, minor=?, location=?, user_id=?, notify_type=?
        WHERE id=?
    ");

    /* ✨ แก้ bind_param: 7 ตัว ต้องใช้“siisisi” */
    $stmt->bind_param("siisisi", $uuid, $major, $minor, $place, $owner, $notify, $id);
    $stmt->execute();

    swal("สำเร็จ", "แก้ไขข้อมูลสำเร็จ", "success", "beacons.php");
}

/* ==========================================================
   DELETE BEACON
========================================================== */
if (isset($_GET['del'])) {

    $id = intval($_GET['del']);

    $q = $conn->query("SELECT user_id FROM beacons WHERE id=$id");
    $b = $q->fetch_assoc();

    if (!$b) {
        swal("ผิดพลาด", "ไม่พบข้อมูล Beacon", "error", "beacons.php");
        exit;
    }

    if ($ROLE == "user" && $b['user_id'] != $USER_ID) {
        swal("สิทธิ์ไม่เพียงพอ", "คุณไม่มีสิทธิ์ลบ Beacon นี้", "error", "beacons.php");
        exit;
    }

    staff_cannot_edit_admin($b['user_id'], $conn);

    $conn->query("DELETE FROM beacons WHERE id=$id");

    swal("สำเร็จ", "ลบ Beacon สำเร็จ", "success", "beacons.php");
}
?>

<style>
.beacon-card {
    border-radius: 12px;
    padding: 15px;
    background: #fff;
    border: 1px solid #e0e0e0;
    transition: 0.2s;
}
.beacon-card:hover {
    box-shadow: 0 4px 18px rgba(0,0,0,0.12);
    transform: translateY(-3px);
}
.beacon-icon {
    font-size: 45px;
    color: #0d6efd;
}
.fab-add {
    position: fixed;
    bottom: 25px;
    right: 25px;
    background: #0d6efd;
    color: #fff;
    width: 60px;
    height: 60px;
    border-radius: 50%;
    font-size: 32px;
    text-align: center;
    line-height: 60px;
    cursor: pointer;
    box-shadow: 0 4px 16px rgba(0,0,0,0.3);
}
</style>

<h3><i class="bi bi-broadcast"></i> จัดการ Beacon</h3>
<hr>

<div class="row g-3">

<?php
$sql = "
    SELECT beacons.*, users.fullname
    FROM beacons
    LEFT JOIN users ON beacons.user_id = users.id
    $filter
    ORDER BY beacons.id DESC
";
$res = $conn->query($sql);

while ($b = $res->fetch_assoc()):
?>

<div class="col-md-6 col-lg-4">
    <div class="beacon-card">

        <div class="d-flex">
            <div><i class="bi bi-router beacon-icon"></i></div>
            <div class="ms-3 flex-grow-1">
                <strong>UUID:</strong> <?= $b['uuid'] ?><br>
                <strong>Major:</strong> <?= $b['major'] ?>
                <strong>Minor:</strong> <?= $b['minor'] ?><br>
                <strong>ตำแหน่ง:</strong> <?= $b['location'] ?><br>

                <strong>แจ้งเตือน:</strong>
                <?php 
                if ($b['notify_type'] == 'ALWAYS') echo 'แจ้งทุกครั้ง';
                else if ($b['notify_type'] == 'ONCE_PER_DAY') echo 'วันละครั้ง';
                else echo 'ไม่แจ้งเตือน';
                ?>
                <br>

                <?php if ($ROLE != 'user'): ?>
                    <small class="text-muted">เจ้าของ:
                        <?= $b['fullname'] ? $b['fullname'] : "-" ?>
                    </small>
                <?php endif; ?>
            </div>
        </div>

        <div class="text-end mt-3">
            <?php if ($ROLE == 'admin' || $ROLE == 'staff' || $b['user_id'] == $USER_ID): ?>

            <button class="btn btn-warning btn-sm"
                    data-bs-toggle="modal"
                    data-bs-target="#editModal<?= $b['id'] ?>">
                <i class="bi bi-pencil-square"></i> แก้ไข
            </button>

            <a href="javascript:void(0)" onclick="confirmDelete(<?= $b['id'] ?>)"
               class="btn btn-danger btn-sm">
               <i class="bi bi-trash"></i> ลบ
            </a>

            <?php endif; ?>
        </div>

    </div>
</div>

<!-- DELETE CONFIRM -->
<script>
function confirmDelete(id) {
    Swal.fire({
        title: "ลบ Beacon?",
        text: "แน่ใจหรือว่าต้องการลบรายการนี้",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "ลบ",
        cancelButtonText: "ยกเลิก"
    }).then((r) => {
        if (r.isConfirmed) {
            window.location = "beacons.php?del=" + id;
        }
    });
}
</script>

<!-- EDIT MODAL -->
<div class="modal fade" id="editModal<?= $b['id'] ?>">
  <div class="modal-dialog">
    <div class="modal-content">

      <form method="post">
        <div class="modal-header">
          <h5 class="modal-title">แก้ไข Beacon</h5>
          <button class="btn-close" data-bs-dismiss="modal"></button>
        </div>

        <div class="modal-body">

          <input type="hidden" name="beacon_id" value="<?= $b['id'] ?>">

          <label>UUID</label>
          <input type="text" name="uuid" class="form-control mb-2"
                 value="<?= $b['uuid'] ?>" required>

          <label>Major</label>
          <input type="number" name="major" class="form-control mb-2"
                 value="<?= $b['major'] ?>" required>

          <label>Minor</label>
          <input type="number" name="minor" class="form-control mb-2"
                 value="<?= $b['minor'] ?>" required>

          <label>ตำแหน่ง</label>
          <input type="text" name="place" class="form-control mb-2"
                 value="<?= $b['location'] ?>">

          <label>รูปแบบการแจ้งเตือน</label>
          <select name="notify_type" class="form-select mb-2">
              <option value="ALWAYS"      <?= ($b['notify_type']=='ALWAYS') ? 'selected' : '' ?>>แจ้งทุกครั้ง</option>
              <option value="ONCE_PER_DAY" <?= ($b['notify_type']=='ONCE_PER_DAY') ? 'selected' : '' ?>>วันละครั้ง</option>
              <option value="NONE"         <?= ($b['notify_type']=='NONE') ? 'selected' : '' ?>>ไม่แจ้งเตือน</option>
          </select>

          <?php if ($ROLE != "user"): ?>
          <label>เจ้าของ Beacon</label>
          <select name="user_id" class="form-select mb-2">
            <?php
            $u = $conn->query("SELECT id, fullname, role FROM users ORDER BY fullname");
            while ($x = $u->fetch_assoc()):
            ?>
              <option value="<?= $x['id'] ?>"
                <?= ($b['user_id'] == $x['id']) ? "selected" : "" ?>
                <?= ($ROLE=='staff' && $x['role']=='admin') ? "disabled" : "" ?>>
                <?= $x['fullname'] ?> (<?= $x['role'] ?>)
              </option>
            <?php endwhile; ?>
          </select>
          <?php else: ?>
          <input type="hidden" name="user_id" value="<?= $b['user_id'] ?>">
          <?php endif; ?>

        </div>

        <div class="modal-footer">
          <button name="edit_beacon" class="btn btn-success">
            <i class="bi bi-check-lg"></i> บันทึก
          </button>
        </div>

      </form>

    </div>
  </div>
</div>

<?php endwhile; ?>
</div>

<!-- ADD BEACON BUTTON -->
<div class="fab-add" data-bs-toggle="modal" data-bs-target="#addModal">+</div>

<!-- ADD MODAL -->
<div class="modal fade" id="addModal">
  <div class="modal-dialog">
    <div class="modal-content">

      <form method="post">

        <div class="modal-header">
          <h5 class="modal-title">เพิ่ม Beacon ใหม่</h5>
          <button class="btn-close" data-bs-dismiss="modal"></button>
        </div>

        <div class="modal-body">

          <label>UUID</label>
          <input type="text" name="uuid" class="form-control mb-2" required>

          <label>Major</label>
          <input type="number" name="major" class="form-control mb-2" required>

          <label>Minor</label>
          <input type="number" name="minor" class="form-control mb-2" required>

          <label>ตำแหน่ง</label>
          <input type="text" name="place" class="form-control mb-3">

          <label>รูปแบบการแจ้งเตือน</label>
          <select name="notify_type" class="form-select mb-3">
              <option value="ALWAYS">แจ้งทุกครั้ง</option>
              <option value="ONCE_PER_DAY">วันละครั้ง</option>
              <option value="NONE">ไม่แจ้งเตือน</option>
          </select>

          <?php if ($ROLE != "user"): ?>
          <label>เจ้าของ Beacon</label>
          <select name="user_id" class="form-select">
            <?php
            /* FIXED: SQL ERROR ต้นเหตุที่ modal ไม่ขึ้น */
            $u = $conn->query("SELECT id, fullname, role FROM users ORDER BY fullname");
            while ($x = $u->fetch_assoc()):
            ?>
              <option value="<?= $x['id'] ?>"
                <?= ($ROLE=='staff' && $x['role']=='admin') ? "disabled" : "" ?>>
                <?= $x['fullname'] ?> (<?= $x['role'] ?>)
              </option>
            <?php endwhile; ?>
          </select>
          <?php else: ?>
          <input type="hidden" name="user_id" value="<?= $USER_ID ?>">
          <?php endif; ?>

        </div>

        <div class="modal-footer">
          <button name="add_beacon" class="btn btn-primary">
            <i class="bi bi-plus-circle"></i> เพิ่ม Beacon
          </button>
        </div>

      </form>

    </div>
  </div>
</div>

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