<?php
$require_admin = true; // This page requires admin privileges
require_once 'php/auth_check.php';
require_once 'php/db_connect.php';

// Fetch malls for the dropdown
$malls = [];
$sql_malls = "SELECT id, name FROM malls ORDER BY name ASC";
$result_malls = $conn->query($sql_malls);
if ($result_malls && $result_malls->num_rows > 0) {
    while ($row = $result_malls->fetch_assoc()) {
        $malls[] = $row;
    }
}

// Fetch units to display (can be filtered by mall later if desired)
$units = [];
// Added mall_name to the query
$sql_units = "SELECT u.*, m.name as mall_name FROM units u JOIN malls m ON u.mall_id = m.id ORDER BY m.name, u.level, u.unit_id_display";
$result_units = $conn->query($sql_units);
if ($result_units && $result_units->num_rows > 0) {
    while ($row = $result_units->fetch_assoc()) {
        $units[] = $row;
    }
}

$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Admin - Unit Management</title>
    <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="css/admin_style.css"> </head>
<body>
    <header>
        <h1>Admin - Unit Management</h1>
        <p>
            Welcome, <?php echo htmlspecialchars($_SESSION["username"]); ?>!
            <a href="index.php?mall=<?php echo isset($_SESSION['selected_mall_slug']) ? $_SESSION['selected_mall_slug'] : '321-clementi'; ?>" style="color:#fff; margin-left:15px;">View Site</a> |
            <a href="php/logout.php" style="color:#fff;">Logout</a>
        </p>
    </header>

    <main class="admin-main">
        <section id="add-edit-unit-section">
            <h2>Add New Unit / Edit Unit</h2>
            <form id="unit-form" action="php/admin_functions.php" method="post" enctype="multipart/form-data">
                <input type="hidden" name="action" id="form-action" value="add_unit">
                <input type="hidden" name="unit_db_id" id="unit_db_id" value="">

                <div class="form-grid">
                    <div class="form-group">
                        <label for="mall_id">Mall:</label>
                        <select name="mall_id" id="mall_id" required>
                            <option value="">Select Mall</option>
                            <?php foreach ($malls as $mall): ?>
                                <option value="<?php echo $mall['id']; ?>"><?php echo htmlspecialchars($mall['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="level">Level (e.g., 1, 2, B1):</label>
                        <input type="text" name="level" id="level" required>
                    </div>
                    <div class="form-group">
                        <label for="unit_id_display">Unit ID (e.g., L1-01):</label>
                        <input type="text" name="unit_id_display" id="unit_id_display" required>
                    </div>
                     <div class="form-group">
                        <label for="status">Status:</label>
                        <select name="status" id="status" required>
                            <option value="Available">Available</option>
                            <option value="Leased">Leased</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="area">Area (e.g., 150 sqm):</label>
                        <input type="text" name="area" id="area">
                    </div>
                    <div class="form-group">
                        <label for="water_point">Water Point:</label>
                        <input type="text" name="water_point" id="water_point">
                    </div>
                    <div class="form-group">
                        <label for="ac_power">A/C Power:</label>
                        <input type="text" name="ac_power" id="ac_power">
                    </div>
                    <div class="form-group">
                        <label for="fcu_units">FCU Units:</label>
                        <input type="text" name="fcu_units" id="fcu_units">
                    </div>
                    <div class="form-group">
                        <label for="elec_isolator">Elec. Isolator:</label>
                        <input type="text" name="elec_isolator" id="elec_isolator">
                    </div>
                    <div class="form-group">
                        <label for="elec_phase">Elec. Phase:</label>
                        <input type="text" name="elec_phase" id="elec_phase">
                    </div>
                    <div class="form-group">
                        <label for="emergency_light">Emergency Lights:</label>
                        <input type="text" name="emergency_light" id="emergency_light">
                    </div>
                    <div class="form-group">
                        <label for="exit_signage">Exit Signage:</label>
                        <input type="text" name="exit_signage" id="exit_signage">
                    </div>
                    <div class="form-group">
                        <label for="pa_speaker">PA Speaker:</label>
                        <input type="text" name="pa_speaker" id="pa_speaker">
                    </div>
                    <div class="form-group">
                        <label for="fibre_port">Fibre Port:</label>
                        <input type="text" name="fibre_port" id="fibre_port">
                    </div>
                    <div class="form-group">
                        <label for="data_port">Data Ports:</label>
                        <input type="text" name="data_port" id="data_port">
                    </div>
                    <div class="form-group">
                        <label for="water_pipe_dia">Water Pipe Dia.:</label>
                        <input type="text" name="water_pipe_dia" id="water_pipe_dia">
                    </div>
                    <div class="form-group">
                        <label for="floor_trap">Floor Traps:</label>
                        <input type="text" name="floor_trap" id="floor_trap">
                    </div>
                    <div class="form-group">
                        <label for="gas_pipe">Gas Pipe:</label>
                        <input type="text" name="gas_pipe" id="gas_pipe">
                    </div>
                    <div class="form-group">
                        <label for="kitchen_ea">Kitchen EA:</label>
                        <input type="text" name="kitchen_ea" id="kitchen_ea">
                    </div>
                    <div class="form-group">
                        <label for="kitchen_fa">Kitchen FA:</label>
                        <input type="text" name="kitchen_fa" id="kitchen_fa">
                    </div>
                    <div class="form-group">
                        <label for="sprinkler">Sprinkler:</label>
                        <input type="text" name="sprinkler" id="sprinkler">
                    </div>

                    <div class="form-group full-width">
                        <label for="other_notes">Other Notes:</label>
                        <textarea name="other_notes" id="other_notes" rows="3"></textarea>
                    </div>

                    <div class="form-group">
                        <label for="detail_plan_image_path">Detail Plan Image Path (e.g., images/details/L1-01.png):</label>
                        <input type="text" name="detail_plan_image_path" id="detail_plan_image_path" placeholder="Relative path from site root">
                        </div>
                    <div class="form-group">
                        <label for="floor_plan_image_path">General Floor Plan Image Path (for this level, e.g., images/malls/321-clementi/level-1.png):</label>
                        <input type="text" name="floor_plan_image_path" id="floor_plan_image_path" placeholder="Relative path from site root">
                    </div>
                </div>

                <div class="form-actions">
                    <button type="submit" class="btn-save">Save Unit</button>
                    <button type="button" class="btn-clear" onclick="clearUnitForm()">Clear Form / New Unit</button>
                </div>
            </form>
            <?php
            if (isset($_SESSION['admin_message'])) {
                echo '<p class="admin-message '.(isset($_SESSION['admin_error']) ? 'error' : 'success').'">'.htmlspecialchars($_SESSION['admin_message']).'</p>';
                unset($_SESSION['admin_message']);
                unset($_SESSION['admin_error']);
            }
            ?>
        </section>

        <section id="manage-units-section">
            <h2>Manage Existing Units</h2>
            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th>Mall</th>
                            <th>Level</th>
                            <th>Unit ID</th>
                            <th>Status</th>
                            <th>Area</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($units)): ?>
                            <?php foreach ($units as $unit): ?>
                            <tr data-unit='<?php echo htmlspecialchars(json_encode($unit), ENT_QUOTES, 'UTF-8'); ?>'>
                                <td><?php echo htmlspecialchars($unit['mall_name']); ?></td>
                                <td><?php echo htmlspecialchars($unit['level']); ?></td>
                                <td><?php echo htmlspecialchars($unit['unit_id_display']); ?></td>
                                <td><?php echo htmlspecialchars($unit['status']); ?></td>
                                <td><?php echo htmlspecialchars($unit['area']); ?></td>
                                <td>
                                    <button class="btn-edit" onclick="populateFormForEdit(this.closest('tr'))">Edit</button>
                                    <form action="php/admin_functions.php" method="post" style="display:inline;" onsubmit="return confirm('Are you sure you want to delete this unit?');">
                                        <input type="hidden" name="action" value="delete_unit">
                                        <input type="hidden" name="unit_db_id" value="<?php echo $unit['id']; ?>">
                                        <button type="submit" class="btn-delete">Delete</button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="6">No units found.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </section>
    </main>

    <footer>
        <p>&copy; <?php echo date("Y"); ?> Admin Panel</p>
    </footer>
    <script src="js/admin_script.js"></script>
</body>
</html>