<?php
session_start();
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$unit_id = $_GET['id'] ?? null;
$unit = null;
$is_edit = false;

if ($unit_id) {
    $is_edit = true;
    $sql = "SELECT * FROM units WHERE unit_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $unit_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $unit = $result->fetch_assoc();
    
    if (!$unit) {
        header('Location: list_units.php');
        exit();
    }
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $property_id = $_POST['property_id'];
    $unit_number = trim($_POST['unit_number']);
    $unit_type_id = $_POST['unit_type_id'] ?? null;
    $floor_level = $_POST['floor_level'] ?? null;
    $bedrooms = $_POST['bedrooms'] ?? 0;
    $bathrooms = $_POST['bathrooms'] ?? 0;
    $rent_amount = $_POST['rent_amount'];
    $deposit_amount = $_POST['deposit_amount'] ?? 0;
    $status = $_POST['status'] ?? 'VACANT';
    $furnishing = $_POST['furnishing'] ?? 'Unfurnished';
    $has_parking = isset($_POST['has_parking']) ? 1 : 0;
    $parking_slot_no = $_POST['parking_slot_no'] ?? null;
    
    if ($is_edit) {
        $sql = "UPDATE units SET property_id = ?, unit_number = ?, unit_type_id = ?, 
                floor_level = ?, bedrooms = ?, bathrooms = ?, rent_amount = ?, 
                deposit_amount = ?, status = ?, furnishing = ?, has_parking = ?, 
                parking_slot_no = ? WHERE unit_id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("isisiiidssisi", $property_id, $unit_number, $unit_type_id, 
                         $floor_level, $bedrooms, $bathrooms, $rent_amount, 
                         $deposit_amount, $status, $furnishing, $has_parking, 
                         $parking_slot_no, $unit_id);
        $success_message = "Unit updated successfully!";
    } else {
        $sql = "INSERT INTO units (property_id, unit_number, unit_type_id, floor_level, 
                                  bedrooms, bathrooms, rent_amount, deposit_amount, 
                                  status, furnishing, has_parking, parking_slot_no, created_at) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("isisiiidssis", $property_id, $unit_number, $unit_type_id, 
                         $floor_level, $bedrooms, $bathrooms, $rent_amount, 
                         $deposit_amount, $status, $furnishing, $has_parking, $parking_slot_no);
        $success_message = "Unit added successfully!";
    }
    
    if ($stmt->execute()) {
        $_SESSION['success_message'] = $success_message;
        header('Location: list_units.php');
        exit();
    } else {
        $error_message = "Error: " . $conn->error;
    }
}

// Get properties
$sql_properties = "SELECT * FROM properties ORDER BY property_name";
$result_properties = $conn->query($sql_properties);

// Get unit types
$sql_types = "SELECT * FROM unit_types ORDER BY name";
$result_types = $conn->query($sql_types);
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => ($is_edit ? 'Edit' : 'Add') . ' Unit')); ?>
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array(
                        'pagetitle' => 'Property Management', 
                        'title' => ($is_edit ? 'Edit' : 'Add') . ' Unit'
                    )); ?>

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">
                                        <?php echo $is_edit ? 'Edit Unit' : 'Add New Unit'; ?>
                                    </h4>
                                </div>
                                <div class="card-body">
                                    <?php if (isset($error_message)): ?>
                                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                            <?php echo htmlspecialchars($error_message); ?>
                                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                        </div>
                                    <?php endif; ?>

                                    <form method="POST" id="unitForm">
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Property <span class="text-danger">*</span></label>
                                                <select class="form-select" name="property_id" required>
                                                    <option value="">Select Property</option>
                                                    <?php while($prop = $result_properties->fetch_assoc()): ?>
                                                        <option value="<?php echo $prop['property_id']; ?>" 
                                                                <?php echo (($unit['property_id'] ?? '') == $prop['property_id']) ? 'selected' : ''; ?>>
                                                            <?php echo htmlspecialchars($prop['property_name']); ?>
                                                        </option>
                                                    <?php endwhile; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Unit Number <span class="text-danger">*</span></label>
                                                <input type="text" class="form-control" name="unit_number" 
                                                       value="<?php echo htmlspecialchars($unit['unit_number'] ?? ''); ?>" 
                                                       required>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Unit Type</label>
                                                <select class="form-select" name="unit_type_id">
                                                    <option value="">Select Type</option>
                                                    <?php while($type = $result_types->fetch_assoc()): ?>
                                                        <option value="<?php echo $type['type_id']; ?>" 
                                                                <?php echo (($unit['unit_type_id'] ?? '') == $type['type_id']) ? 'selected' : ''; ?>>
                                                            <?php echo htmlspecialchars($type['name']); ?>
                                                        </option>
                                                    <?php endwhile; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Floor Level</label>
                                                <input type="number" class="form-control" name="floor_level" 
                                                       value="<?php echo $unit['floor_level'] ?? ''; ?>">
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Status</label>
                                                <select class="form-select" name="status">
                                                    <option value="VACANT" <?php echo ($unit['status'] ?? 'VACANT') == 'VACANT' ? 'selected' : ''; ?>>Vacant</option>
                                                    <option value="OCCUPIED" <?php echo ($unit['status'] ?? '') == 'OCCUPIED' ? 'selected' : ''; ?>>Occupied</option>
                                                    <option value="RESERVED" <?php echo ($unit['status'] ?? '') == 'RESERVED' ? 'selected' : ''; ?>>Reserved</option>
                                                    <option value="MAINTENANCE" <?php echo ($unit['status'] ?? '') == 'MAINTENANCE' ? 'selected' : ''; ?>>Maintenance</option>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-3 mb-3">
                                                <label class="form-label">Bedrooms</label>
                                                <input type="number" class="form-control" name="bedrooms" 
                                                       value="<?php echo $unit['bedrooms'] ?? 0; ?>" min="0">
                                            </div>
                                            <div class="col-md-3 mb-3">
                                                <label class="form-label">Bathrooms</label>
                                                <input type="number" class="form-control" name="bathrooms" 
                                                       value="<?php echo $unit['bathrooms'] ?? 0; ?>" min="0">
                                            </div>
                                            <div class="col-md-3 mb-3">
                                                <label class="form-label">Rent Amount (KES) <span class="text-danger">*</span></label>
                                                <input type="number" class="form-control" name="rent_amount" 
                                                       value="<?php echo $unit['rent_amount'] ?? ''; ?>" 
                                                       step="0.01" required>
                                            </div>
                                            <div class="col-md-3 mb-3">
                                                <label class="form-label">Deposit Amount (KES)</label>
                                                <input type="number" class="form-control" name="deposit_amount" 
                                                       value="<?php echo $unit['deposit_amount'] ?? 0; ?>" 
                                                       step="0.01">
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Furnishing</label>
                                                <select class="form-select" name="furnishing">
                                                    <option value="Unfurnished" <?php echo ($unit['furnishing'] ?? 'Unfurnished') == 'Unfurnished' ? 'selected' : ''; ?>>Unfurnished</option>
                                                    <option value="Semi-Furnished" <?php echo ($unit['furnishing'] ?? '') == 'Semi-Furnished' ? 'selected' : ''; ?>>Semi-Furnished</option>
                                                    <option value="Furnished" <?php echo ($unit['furnishing'] ?? '') == 'Furnished' ? 'selected' : ''; ?>>Furnished</option>
                                                </select>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <div class="form-check mt-4">
                                                    <input class="form-check-input" type="checkbox" name="has_parking" 
                                                           id="has_parking" <?php echo ($unit['has_parking'] ?? 0) ? 'checked' : ''; ?>>
                                                    <label class="form-check-label" for="has_parking">
                                                        Has Parking
                                                    </label>
                                                </div>
                                                <input type="text" class="form-control mt-2" name="parking_slot_no" 
                                                       value="<?php echo htmlspecialchars($unit['parking_slot_no'] ?? ''); ?>" 
                                                       placeholder="Parking slot number" id="parking_slot" 
                                                       style="display: <?php echo ($unit['has_parking'] ?? 0) ? 'block' : 'none'; ?>;">
                                            </div>
                                        </div>

                                        <div class="mt-4">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="ri-save-line align-bottom me-1"></i>
                                                <?php echo $is_edit ? 'Update Unit' : 'Add Unit'; ?>
                                            </button>
                                            <a href="list_units.php" class="btn btn-light ms-2">
                                                <i class="ri-close-line align-bottom me-1"></i>Cancel
                                            </a>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script>
        document.getElementById('has_parking').addEventListener('change', function() {
            document.getElementById('parking_slot').style.display = this.checked ? 'block' : 'none';
        });
    </script>
</body>
</html>
