<?php
require_once __DIR__ . "/auth/init.php";
authorize(); // semua role kecuali guest
$user_id = $_SESSION['user_id'];

// Get Logged in Admin Details for Verification
$stmt = mysqli_prepare($conn, "SELECT role FROM users WHERE id=?");
mysqli_stmt_bind_param($stmt, "i", $user_id);
mysqli_stmt_execute($stmt);
$user_role = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt))['role'] ?? 'guest';

/* =======================================================
   BACKEND ACTION PROCESSING: ADD LOCATION
=========================================================*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_location'])) {
    if ($user_role !== 'admin') {
        $_SESSION['loc_error'] = "Unauthorized access.";
    } else {
        $name = trim($_POST['location_name'] ?? '');
        $desc = trim($_POST['description'] ?? '');

        if ($name === '') {
            $_SESSION['loc_error'] = "Location name is mandatory.";
        } else {
            $add_stmt = mysqli_prepare($conn, "INSERT INTO locations (location_name, description) VALUES (?, ?)");
            $desc_param = ($desc === '') ? null : $desc;
            mysqli_stmt_bind_param($add_stmt, "ss", $name, $desc_param);
            
            if (mysqli_stmt_execute($add_stmt)) {
                $_SESSION['loc_success'] = "Location created successfully.";
            } else {
                $_SESSION['loc_error'] = "Error saving location details.";
            }
        }
    }
    header("Location: location.php");
    exit();
}

/* =======================================================
   BACKEND ACTION PROCESSING: DELETE LOCATION
=========================================================*/
if (isset($_GET['delete_id'])) {
    if ($user_role !== 'admin') {
        $_SESSION['loc_error'] = "Unauthorized access.";
    } else {
        $delete_id = intval($_GET['delete_id']);
        $del_stmt = mysqli_prepare($conn, "DELETE FROM locations WHERE id = ?");
        mysqli_stmt_bind_param($del_stmt, "i", $delete_id);
        
        if (mysqli_stmt_execute($del_stmt)) {
            $_SESSION['loc_success'] = "Location dropped successfully.";
        } else {
            $_SESSION['loc_error'] = "Failed to drop location record.";
        }
    }
    header("Location: location.php");
    exit();
}

// Fetch all registered locations
$locations_result = mysqli_query($conn, "SELECT * FROM locations ORDER BY created_at DESC");
?>

<!DOCTYPE html>
<html>
<head>
    <title>Manage Locations - QRCareTrack</title>
    <link rel="stylesheet" href="assets/style.css">
    <link rel="stylesheet" href="assets/settings.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
    <style>
        .modal { display: none; position: fixed; top:0; left:0; width:100%; height:100%; background: rgba(0,0,0,0.5); justify-content:center; align-items:center; z-index:999; }
        .modal-box { background:#fff; padding:20px; border-radius:8px; width:400px; max-width:90%; position:relative; }
        .modal-header { display:flex; justify-content:space-between; align-items:center; margin-bottom:15px; }
        .modal-header h3 { margin:0; }
        .close { cursor:pointer; font-size:20px; font-weight:bold; }
        .modal-actions { margin-top:20px; display:flex; justify-content:flex-end; gap:10px; }
    </style>
</head>
<body>

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

<div class="main">

    <?php if(isset($_SESSION['loc_error'])): ?>
        <div class="alert error"><?= $_SESSION['loc_error']; unset($_SESSION['loc_error']); ?></div>
    <?php endif; ?>
    <?php if(isset($_SESSION['loc_success'])): ?>
        <div class="alert success"><?= $_SESSION['loc_success']; unset($_SESSION['loc_success']); ?></div>
    <?php endif; ?>

    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
        <h2><a href="settings.php" style="text-decoration:none; color:inherit;"><i class="fas fa-arrow-left"></i></a> Manage Locations</h2>
        <?php if($user_role == "admin"): ?>
            <button class="btn primary" onclick="openModal()">+ Add Location</button>
        <?php endif; ?>
    </div>

    <div class="box">
        <table>
            <thead>
                <tr>
                    <th># ID</th>
                    <th>Location Name</th>
                    <th>Description</th>
                    <th>Created At</th>
                    <?php if($user_role == "admin"): ?><th>Action</th><?php endif; ?>
                </tr>
            </thead>
            <tbody>
                <?php if(mysqli_num_rows($locations_result) > 0): ?>
                    <?php while($row = mysqli_fetch_assoc($locations_result)): ?>
                    <tr>
                        <td><strong># <?= $row['id'] ?></strong></td>
                        <td><?= htmlspecialchars($row['location_name']) ?></td>
                        <td><?= htmlspecialchars($row['description'] ?? '-') ?></td>
                        <td><?= date('d M Y, h:i A', strtotime($row['created_at'])) ?></td>
                        <?php if($user_role == "admin"): ?>
                        <td>
                            <a href="location.php?delete_id=<?= $row['id'] ?>" class="btn-sm danger" style="background:#e74c3c; color:white; text-decoration:none; padding:5px 10px; border-radius:4px;" onclick="return confirm('Are you sure you want to permanently delete this location definition?');">
                                <i class="fas fa-trash-alt"></i> Delete
                            </a>
                        </td>
                        <?php endif; ?>
                    </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="<?= ($user_role == 'admin') ? 5 : 4 ?>" style="text-align: center; color: #7f8c8d;">No system locations tracked yet.</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<div id="addLocationModal" class="modal">
    <div class="modal-box">
        <div class="modal-header">
            <h3>Add System Location</h3>
            <span class="close" onclick="closeModal()">&times;</span>
        </div>
        <form method="POST" action="location.php">
            <label style="display:block; margin-bottom:5px; font-weight:bold;">Location Name *</label>
            <input type="text" name="location_name" required placeholder="e.g. Server Room, Block B Level 3" style="width:100%; padding:8px; border:1px solid #ddd; border-radius:4px; margin-bottom:15px; box-sizing:border-box;">

            <label style="display:block; margin-bottom:5px; font-weight:bold;">Description</label>
            <textarea name="description" placeholder="Optional layout or function notes..." style="width:100%; padding:8px; border:1px solid #ddd; border-radius:4px; height:80px; resize:none; box-sizing:border-box; font-family:inherit;"></textarea>

            <div class="modal-actions">
                <button type="submit" name="add_location" class="btn primary">Save Location</button>
            </div>
        </form>
    </div>
</div>

<script>
    const modal = document.getElementById("addLocationModal");
    function openModal() { modal.style.display = "flex"; }
    function closeModal() { modal.style.display = "none"; }
    
    // Close modal window if user clicks background frame area
    window.onclick = function(event) {
        if (event.target == modal) { closeModal(); }
    }
</script>

</body>
</html>