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

// Check if the user is not logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$property_id = $_GET['id'] ?? null;
$property = null;
$is_edit = false;

// Define property types from enum
$property_types = [
    'Apartment Complex',
    'Commercial Tower', 
    'Gated Community',
    'Mall',
    'Single Unit',
    'Land'
];

// If editing, fetch property data
if ($property_id) {
    $is_edit = true;
    $sql = "SELECT * FROM properties WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $property_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $property = $result->fetch_assoc();
    
    if (!$property) {
        $_SESSION['error_message'] = "Property not found!";
        header('Location: list_properties.php');
        exit();
    }
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $property_name = trim($_POST['property_name']);
    $property_type = $_POST['property_type'];
    $owner_id = $_POST['owner_id'] ?? $_SESSION['user_id'];
    $manager_id = $_POST['manager_id'] ?? null;
    $location_area = trim($_POST['location_area']);
    $street_address = trim($_POST['street_address']);
    $city = trim($_POST['city']);
    $total_floors = $_POST['total_floors'] ?? 1;
    $total_units = $_POST['total_units'] ?? 0;
    $description = trim($_POST['description']);
    $construction_year = $_POST['construction_year'] ?? null;
    $l_r_number = trim($_POST['l_r_number'] ?? '');
    
    if ($is_edit) {
        $sql = "UPDATE properties SET 
                name = ?, type = ?, owner_id = ?, manager_id = ?,
                location_area = ?, street_address = ?, city = ?, 
                total_floors = ?, total_units = ?, description = ?,
                construction_year = ?, l_r_number = ?
                WHERE id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ssiisssiiissi", 
            $property_name, $property_type, $owner_id, $manager_id,
            $location_area, $street_address, $city, 
            $total_floors, $total_units, $description,
            $construction_year, $l_r_number, $property_id
        );
        $success_message = "Property updated successfully!";
    } else {
        $sql = "INSERT INTO properties (
                    name, type, owner_id, manager_id, location_area, 
                    street_address, city, total_floors, total_units, 
                    description, construction_year, l_r_number, created_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ssiisssiisss", 
            $property_name, $property_type, $owner_id, $manager_id,
            $location_area, $street_address, $city, 
            $total_floors, $total_units, $description,
            $construction_year, $l_r_number
        );
        $success_message = "Property added successfully!";
    }
    
    if ($stmt->execute()) {
        $_SESSION['success_message'] = $success_message;
        header('Location: list_properties.php');
        exit();
    } else {
        $error_message = "Error: " . $conn->error;
    }
}

// Get landlords (role_id = 2) for owner dropdown
$sql_owners = "SELECT id, CONCAT(first_name, ' ', last_name) as full_name 
               FROM users WHERE role_id = 2 AND status = 'active' 
               ORDER BY first_name";
$result_owners = $conn->query($sql_owners);

// Get property managers (role_id = 3) for manager dropdown
$sql_managers = "SELECT id, CONCAT(first_name, ' ', last_name) as full_name 
                FROM users WHERE role_id = 3 AND status = 'active' 
                ORDER BY first_name";
$result_managers = $conn->query($sql_managers);
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => ($is_edit ? 'Edit' : 'Add') . ' Property')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- Select2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
    
    <style>
        .section-header {
            border-left: 4px solid #405189;
            padding-left: 12px;
            margin-bottom: 20px;
            margin-top: 24px;
        }
        .section-header h5 {
            color: #405189;
            font-weight: 600;
            margin-bottom: 4px;
        }
        .section-header p {
            color: #878a99;
            font-size: 13px;
            margin: 0;
        }
        .form-icon {
            position: absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #878a99;
            z-index: 5;
        }
        .icon-input-wrapper {
            position: relative;
        }
        .icon-input-wrapper .form-control,
        .icon-input-wrapper .form-select {
            padding-left: 38px;
        }
        .card {
            box-shadow: 0 0.75rem 1.5rem rgba(18,38,63,.03);
            border: 1px solid #e9ebec;
        }
        .card-header {
            background: linear-gradient(135deg, #405189 0%, #556ee6 100%);
            color: white;
            border: none;
            padding: 1.5rem;
        }
        .card-header h4 {
            color: white;
            margin: 0;
            font-weight: 600;
        }
        .btn-primary {
            background: linear-gradient(135deg, #405189 0%, #556ee6 100%);
            border: none;
            padding: 0.6rem 1.5rem;
            font-weight: 500;
        }
        .btn-primary:hover {
            background: linear-gradient(135deg, #556ee6 0%, #405189 100%);
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(64,81,137,.2);
        }
        .required-badge {
            background: #f06548;
            color: white;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 11px;
            font-weight: 600;
            margin-left: 4px;
        }
        .select2-container--bootstrap-5 .select2-selection {
            padding-left: 38px;
        }
    </style>
</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') . ' Property'
                    )); ?>

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0">
                                            <i class="ri-building-line fs-24 me-2"></i>
                                        </div>
                                        <div class="flex-grow-1">
                                            <h4 class="mb-0">
                                                <?php echo $is_edit ? 'Edit Property Details' : 'Add New Property'; ?>
                                            </h4>
                                            <p class="text-white-50 mb-0 mt-1" style="font-size: 13px;">
                                                <?php echo $is_edit ? 'Update property information' : 'Fill in the details to add a new property to your portfolio'; ?>
                                            </p>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-body p-4">
                                    <?php if (isset($error_message)): ?>
                                        <div class="alert alert-danger alert-dismissible alert-border-left fade show" role="alert">
                                            <i class="ri-error-warning-line me-2 align-middle fs-16"></i>
                                            <?php echo htmlspecialchars($error_message); ?>
                                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                        </div>
                                    <?php endif; ?>

                                    <form method="POST" id="propertyForm">
                                        <!-- Basic Information Section -->
                                        <div class="section-header">
                                            <h5><i class="ri-information-line me-2"></i>Basic Information</h5>
                                            <p>Primary details about the property</p>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-8 mb-3">
                                                <label class="form-label">Property Name 
                                                    <span class="required-badge">REQUIRED</span>
                                                </label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-home-4-line form-icon"></i>
                                                    <input type="text" class="form-control" name="property_name" 
                                                           value="<?php echo htmlspecialchars($property['name'] ?? ''); ?>" 
                                                           required placeholder="e.g., Sunrise Apartments">
                                                </div>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Property Type 
                                                    <span class="required-badge">REQUIRED</span>
                                                </label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-building-2-line form-icon"></i>
                                                    <select class="form-select select2" name="property_type" required>
                                                        <option value="">Select Type</option>
                                                        <?php foreach($property_types as $type): ?>
                                                            <option value="<?php echo $type; ?>" 
                                                                    <?php echo (($property['type'] ?? '') == $type) ? 'selected' : ''; ?>>
                                                                <?php echo htmlspecialchars($type); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Ownership Section -->
                                        <div class="section-header">
                                            <h5><i class="ri-user-3-line me-2"></i>Ownership & Management</h5>
                                            <p>Assign owner and property manager</p>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Property Owner 
                                                    <span class="required-badge">REQUIRED</span>
                                                </label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-user-star-line form-icon"></i>
                                                    <select class="form-select select2" name="owner_id" required>
                                                        <option value="">Select Owner</option>
                                                        <?php while($owner = $result_owners->fetch_assoc()): ?>
                                                            <option value="<?php echo $owner['id']; ?>" 
                                                                    <?php echo (($property['owner_id'] ?? $_SESSION['user_id']) == $owner['id']) ? 'selected' : ''; ?>>
                                                                <?php echo htmlspecialchars($owner['full_name']); ?>
                                                            </option>
                                                        <?php endwhile; ?>
                                                    </select>
                                                </div>
                                                <small class="text-muted">
                                                    <i class="ri-information-line"></i> The landlord who owns this property
                                                </small>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Property Manager 
                                                    <span class="badge bg-soft-info text-info">Optional</span>
                                                </label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-user-settings-line form-icon"></i>
                                                    <select class="form-select select2" name="manager_id">
                                                        <option value="">Select Manager</option>
                                                        <?php while($manager = $result_managers->fetch_assoc()): ?>
                                                            <option value="<?php echo $manager['id']; ?>" 
                                                                    <?php echo (($property['manager_id'] ?? '') == $manager['id']) ? 'selected' : ''; ?>>
                                                                <?php echo htmlspecialchars($manager['full_name']); ?>
                                                            </option>
                                                        <?php endwhile; ?>
                                                    </select>
                                                </div>
                                                <small class="text-muted">
                                                    <i class="ri-information-line"></i> Assigned property manager
                                                </small>
                                            </div>
                                        </div>

                                        <!-- Property Details Section -->
                                        <div class="section-header">
                                            <h5><i class="ri-bar-chart-box-line me-2"></i>Property Details</h5>
                                            <p>Structural and capacity information</p>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Total Floors</label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-stack-line form-icon"></i>
                                                    <input type="number" class="form-control" name="total_floors" 
                                                           value="<?php echo $property['total_floors'] ?? 1; ?>" min="1" placeholder="e.g., 5">
                                                </div>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Total Units</label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-home-gear-line form-icon"></i>
                                                    <input type="number" class="form-control" name="total_units" 
                                                           value="<?php echo $property['total_units'] ?? 0; ?>" min="0" placeholder="e.g., 24">
                                                </div>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Construction Year</label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-calendar-line form-icon"></i>
                                                    <input type="number" class="form-control" name="construction_year" 
                                                           value="<?php echo $property['construction_year'] ?? ''; ?>" 
                                                           min="1900" max="<?php echo date('Y'); ?>" placeholder="e.g., 2020">
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Location Section -->
                                        <div class="section-header">
                                            <h5><i class="ri-map-pin-line me-2"></i>Location Information</h5>
                                            <p>Property address and geographic details</p>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Location Area 
                                                    <span class="required-badge">REQUIRED</span>
                                                </label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-road-map-line form-icon"></i>
                                                    <input type="text" class="form-control" name="location_area" 
                                                           value="<?php echo htmlspecialchars($property['location_area'] ?? ''); ?>" 
                                                           placeholder="e.g., Kilimani, Westlands" required>
                                                </div>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">City</label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-map-2-line form-icon"></i>
                                                    <input type="text" class="form-control" name="city" 
                                                           value="<?php echo htmlspecialchars($property['city'] ?? ''); ?>" 
                                                           placeholder="e.g., Nairobi">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-8 mb-3">
                                                <label class="form-label">Street Address</label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-home-2-line form-icon"></i>
                                                    <input type="text" class="form-control" name="street_address" 
                                                           value="<?php echo htmlspecialchars($property['street_address'] ?? ''); ?>" 
                                                           placeholder="e.g., 123 Main Street, Off Argwings Kodhek Road">
                                                </div>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">L.R. Number</label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-file-list-3-line form-icon"></i>
                                                    <input type="text" class="form-control" name="l_r_number" 
                                                           value="<?php echo htmlspecialchars($property['l_r_number'] ?? ''); ?>" 
                                                           placeholder="Land Reference Number">
                                                </div>
                                                <small class="text-muted">
                                                    <i class="ri-information-line"></i> Official land registration number
                                                </small>
                                            </div>
                                        </div>

                                        <!-- Additional Information Section -->
                                        <div class="section-header">
                                            <h5><i class="ri-file-text-line me-2"></i>Additional Information</h5>
                                            <p>Description and other relevant details</p>
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">Property Description</label>
                                            <textarea class="form-control" name="description" rows="5" 
                                                      placeholder="Describe the property, amenities, features, nearby facilities, etc."><?php echo htmlspecialchars($property['description'] ?? ''); ?></textarea>
                                            <small class="text-muted">
                                                <i class="ri-information-line"></i> Include amenities like parking, security, gym, swimming pool, etc.
                                            </small>
                                        </div>

                                        <!-- Form Actions -->
                                        <div class="mt-4 pt-3 border-top">
                                            <button type="submit" class="btn btn-primary btn-lg">
                                                <i class="ri-save-line align-bottom me-1"></i>
                                                <?php echo $is_edit ? 'Update Property' : 'Add Property'; ?>
                                            </button>
                                            <a href="list_properties.php" class="btn btn-light btn-lg 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'; ?>
    
    <!-- Select2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Initialize Select2 on all select elements
            $('.select2').select2({
                theme: 'bootstrap-5',
                width: '100%',
                placeholder: function(){
                    $(this).data('placeholder');
                }
            });
            
            // Form validation enhancement
            $('#propertyForm').on('submit', function(e) {
                let isValid = true;
                
                // Check required fields
                $(this).find('[required]').each(function() {
                    if (!$(this).val()) {
                        isValid = false;
                        $(this).addClass('is-invalid');
                    } else {
                        $(this).removeClass('is-invalid');
                    }
                });
                
                if (!isValid) {
                    e.preventDefault();
                    // Show error message
                    $('html, body').animate({
                        scrollTop: $('.is-invalid').first().offset().top - 100
                    }, 500);
                }
            });
            
            // Remove invalid class on input
            $('input, select, textarea').on('change keyup', function() {
                if ($(this).val()) {
                    $(this).removeClass('is-invalid');
                }
            });
        });
    </script>
</body>
</html>