<?php
session_start();
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
    header("location: login.php");
    exit;
}

require_once "includes/config.php";

// Initialize variables
$title = $description = $price = $address = $city = $state = $zip_code = $property_type = $status = $bedrooms = $bathrooms = $area = $year_built = '';
$title_err = $description_err = $price_err = $address_err = $city_err = $state_err = $zip_code_err = $property_type_err = $status_err = $bedrooms_err = $bathrooms_err = $area_err = $year_built_err = '';

// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
    
    // Validate title
    if(empty(trim($_POST["title"]))){
        $title_err = "Please enter a title for the property.";
    } else{
        $title = trim($_POST["title"]);
    }
    
    // Validate description
    if(empty(trim($_POST["description"]))){
        $description_err = "Please enter a description for the property.";     
    } else{
        $description = trim($_POST["description"]);
    }
    
    // Validate price
    if(empty(trim($_POST["price"]))){
        $price_err = "Please enter the property price.";     
    } elseif(!is_numeric(trim($_POST["price"]))){
        $price_err = "Price must be a number.";
    } else{
        $price = trim($_POST["price"]);
    }
    
    // Validate address
    if(empty(trim($_POST["address"]))){
        $address_err = "Please enter the property address.";     
    } else{
        $address = trim($_POST["address"]);
    }
    
    // Validate city
    if(empty(trim($_POST["city"]))){
        $city_err = "Please enter the city.";     
    } else{
        $city = trim($_POST["city"]);
    }
    
    // Validate state
    if(empty(trim($_POST["state"]))){
        $state_err = "Please select a state.";     
    } else{
        $state = trim($_POST["state"]);
    }
    
    // Validate zip code
    if(empty(trim($_POST["zip_code"]))){
        $zip_code_err = "Please enter the zip code.";     
    } else{
        $zip_code = trim($_POST["zip_code"]);
    }
    
    // Validate property type
    if(empty(trim($_POST["property_type"]))){
        $property_type_err = "Please select a property type.";     
    } else{
        $property_type = trim($_POST["property_type"]);
    }
    
    // Validate status
    if(empty(trim($_POST["status"]))){
        $status_err = "Please select a status.";     
    } else{
        $status = trim($_POST["status"]);
    }
    
    // Validate bedrooms
    if(empty(trim($_POST["bedrooms"]))){
        $bedrooms_err = "Please enter the number of bedrooms.";     
    } elseif(!ctype_digit(trim($_POST["bedrooms"]))){
        $bedrooms_err = "Bedrooms must be a whole number.";
    } else{
        $bedrooms = trim($_POST["bedrooms"]);
    }
    
    // Validate bathrooms
    if(empty(trim($_POST["bathrooms"]))){
        $bathrooms_err = "Please enter the number of bathrooms.";     
    } elseif(!is_numeric(trim($_POST["bathrooms"]))){
        $bathrooms_err = "Bathrooms must be a number.";
    } else{
        $bathrooms = trim($_POST["bathrooms"]);
    }
    
    // Validate area
    if(empty(trim($_POST["area"]))){
        $area_err = "Please enter the property area in square feet.";     
    } elseif(!is_numeric(trim($_POST["area"]))){
        $area_err = "Area must be a number.";
    } else{
        $area = trim($_POST["area"]);
    }
    
    // Validate year built
    if(empty(trim($_POST["year_built"]))){
        $year_built_err = "Please enter the year the property was built.";     
    } elseif(!ctype_digit(trim($_POST["year_built"])) || strlen(trim($_POST["year_built"])) != 4){
        $year_built_err = "Please enter a valid year.";
    } else{
        $year_built = trim($_POST["year_built"]);
    }
    
    // Check input errors before inserting in database
    if(empty($title_err) && empty($description_err) && empty($price_err) && empty($address_err) && 
       empty($city_err) && empty($state_err) && empty($zip_code_err) && empty($property_type_err) && 
       empty($status_err) && empty($bedrooms_err) && empty($bathrooms_err) && empty($area_err) && 
       empty($year_built_err)){
        
        // Prepare an insert statement
        $sql = "INSERT INTO properties (title, description, price, address, city, state, zip_code, 
                                      property_type, status, bedrooms, bathrooms, area, year_built, 
                                      created_by, created_at) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
        
        if($stmt = $conn->prepare($sql)){
            // Bind variables to the prepared statement as parameters
            $stmt->bind_param("ssdssssssiidii", $param_title, $param_description, $param_price, 
                            $param_address, $param_city, $param_state, $param_zip_code, 
                            $param_property_type, $param_status, $param_bedrooms, $param_bathrooms, 
                            $param_area, $param_year_built, $param_created_by);
            
            // Set parameters
            $param_title = $title;
            $param_description = $description;
            $param_price = $price;
            $param_address = $address;
            $param_city = $city;
            $param_state = $state;
            $param_zip_code = $zip_code;
            $param_property_type = $property_type;
            $param_status = $status;
            $param_bedrooms = $bedrooms;
            $param_bathrooms = $bathrooms;
            $param_area = $area;
            $param_year_built = $year_built;
            $param_created_by = $_SESSION['id'];
            
            // Attempt to execute the prepared statement
            if($stmt->execute()){
                // Redirect to properties page
                header("location: properties.php");
                exit();
            } else{
                echo "Oops! Something went wrong. Please try again later.";
            }
            
            // Close statement
            $stmt->close();
        }
    }
    
    // Close connection
    $conn->close();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add New Property - Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body {
            background-color: #f8f9fa;
            padding: 20px;
        }
        .form-container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 0 15px rgba(0,0,0,0.1);
        }
        .form-title {
            color: #4361ee;
            margin-bottom: 25px;
            padding-bottom: 10px;
            border-bottom: 2px solid #f0f0f0;
        }
        .form-label {
            font-weight: 500;
        }
        .required:after {
            content: " *";
            color: red;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-lg-10">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2 class="mb-0">Add New Property</h2>
                    <a href="properties.php" class="btn btn-outline-secondary">
                        <i class="fas fa-arrow-left me-2"></i>Back to Properties
                    </a>
                </div>
                
                <div class="form-container">
                    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" id="propertyForm">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="title" class="form-label required">Property Title</label>
                                    <input type="text" class="form-control <?php echo (!empty($title_err)) ? 'is-invalid' : ''; ?>" 
                                           id="title" name="title" value="<?php echo $title; ?>" required>
                                    <div class="invalid-feedback"><?php echo $title_err; ?></div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="description" class="form-label required">Description</label>
                                    <textarea class="form-control <?php echo (!empty($description_err)) ? 'is-invalid' : ''; ?>" 
                                              id="description" name="description" rows="3" required><?php echo $description; ?></textarea>
                                    <div class="invalid-feedback"><?php echo $description_err; ?></div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label for="price" class="form-label required">Price ($)</label>
                                            <input type="number" class="form-control <?php echo (!empty($price_err)) ? 'is-invalid' : ''; ?>" 
                                                   id="price" name="price" value="<?php echo $price; ?>" required>
                                            <div class="invalid-feedback"><?php echo $price_err; ?></div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label for="property_type" class="form-label required">Property Type</label>
                                            <select class="form-select <?php echo (!empty($property_type_err)) ? 'is-invalid' : ''; ?>" 
                                                    id="property_type" name="property_type" required>
                                                <option value="">Select Type</option>
                                                <option value="House" <?php echo ($property_type == 'House') ? 'selected' : ''; ?>>House</option>
                                                <option value="Apartment" <?php echo ($property_type == 'Apartment') ? 'selected' : ''; ?>>Apartment</option>
                                                <option value="Condo" <?php echo ($property_type == 'Condo') ? 'selected' : ''; ?>>Condo</option>
                                                <option value="Townhouse" <?php echo ($property_type == 'Townhouse') ? 'selected' : ''; ?>>Townhouse</option>
                                                <option value="Land" <?php echo ($property_type == 'Land') ? 'selected' : ''; ?>>Land</option>
                                            </select>
                                            <div class="invalid-feedback"><?php echo $property_type_err; ?></div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label for="bedrooms" class="form-label required">Bedrooms</label>
                                            <input type="number" class="form-control <?php echo (!empty($bedrooms_err)) ? 'is-invalid' : ''; ?>" 
                                                   id="bedrooms" name="bedrooms" value="<?php echo $bedrooms; ?>" required>
                                            <div class="invalid-feedback"><?php echo $bedrooms_err; ?></div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label for="bathrooms" class="form-label required">Bathrooms</label>
                                            <input type="number" step="0.1" class="form-control <?php echo (!empty($bathrooms_err)) ? 'is-invalid' : ''; ?>" 
                                                   id="bathrooms" name="bathrooms" value="<?php echo $bathrooms; ?>" required>
                                            <div class="invalid-feedback"><?php echo $bathrooms_err; ?></div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label for="area" class="form-label required">Area (sq ft)</label>
                                            <input type="number" class="form-control <?php echo (!empty($area_err)) ? 'is-invalid' : ''; ?>" 
                                                   id="area" name="area" value="<?php echo $area; ?>" required>
                                            <div class="invalid-feedback"><?php echo $area_err; ?></div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label for="year_built" class="form-label required">Year Built</label>
                                            <input type="number" class="form-control <?php echo (!empty($year_built_err)) ? 'is-invalid' : ''; ?>" 
                                                   id="year_built" name="year_built" value="<?php echo $year_built; ?>" required>
                                            <div class="invalid-feedback"><?php echo $year_built_err; ?></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="address" class="form-label required">Address</label>
                                    <input type="text" class="form-control <?php echo (!empty($address_err)) ? 'is-invalid' : ''; ?>" 
                                           id="address" name="address" value="<?php echo $address; ?>" required>
                                    <div class="invalid-feedback"><?php echo $address_err; ?></div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label for="city" class="form-label required">City</label>
                                            <input type="text" class="form-control <?php echo (!empty($city_err)) ? 'is-invalid' : ''; ?>" 
                                                   id="city" name="city" value="<?php echo $city; ?>" required>
                                            <div class="invalid-feedback"><?php echo $city_err; ?></div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label for="state" class="form-label required">State</label>
                                            <select class="form-select <?php echo (!empty($state_err)) ? 'is-invalid' : ''; ?>" 
                                                    id="state" name="state" required>
                                                <option value="">Select State</option>
                                                <option value="AL" <?php echo ($state == 'AL') ? 'selected' : ''; ?>>Alabama</option>
                                                <option value="AK" <?php echo ($state == 'AK') ? 'selected' : ''; ?>>Alaska</option>
                                                <!-- Add more states as needed -->
                                                <option value="CA" <?php echo ($state == 'CA') ? 'selected' : ''; ?>>California</option>
                                                <option value="NY" <?php echo ($state == 'NY') ? 'selected' : ''; ?>>New York</option>
                                                <option value="TX" <?php echo ($state == 'TX') ? 'selected' : ''; ?>>Texas</option>
                                            </select>
                                            <div class="invalid-feedback"><?php echo $state_err; ?></div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="zip_code" class="form-label required">ZIP Code</label>
                                    <input type="text" class="form-control <?php echo (!empty($zip_code_err)) ? 'is-invalid' : ''; ?>" 
                                           id="zip_code" name="zip_code" value="<?php echo $zip_code; ?>" required>
                                    <div class="invalid-feedback"><?php echo $zip_code_err; ?></div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="status" class="form-label required">Status</label>
                                    <select class="form-select <?php echo (!empty($status_err)) ? 'is-invalid' : ''; ?>" 
                                            id="status" name="status" required>
                                        <option value="">Select Status</option>
                                        <option value="For Sale" <?php echo ($status == 'For Sale') ? 'selected' : ''; ?>>For Sale</option>
                                        <option value="Pending" <?php echo ($status == 'Pending') ? 'selected' : ''; ?>>Pending</option>
                                        <option value="Sold" <?php echo ($status == 'Sold') ? 'selected' : ''; ?>>Sold</option>
                                        <option value="Rent" <?php echo ($status == 'Rent') ? 'selected' : ''; ?>>For Rent</option>
                                        <option value="Leased" <?php echo ($status == 'Leased') ? 'selected' : ''; ?>>Leased</option>
                                    </select>
                                    <div class="invalid-feedback"><?php echo $status_err; ?></div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="features" class="form-label">Features (Optional)</label>
                                    <textarea class="form-control" id="features" name="features" rows="3" 
                                              placeholder="Enter property features separated by commas"><?php echo $features; ?></textarea>
                                </div>
                            </div>
                        </div>
                        
                        <div class="d-grid gap-2 d-md-flex justify-content-md-end mt-4">
                            <button type="reset" class="btn btn-outline-secondary me-md-2">
                                <i class="fas fa-undo me-1"></i> Reset
                            </button>
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save me-1"></i> Save Property
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Simple form validation
        document.getElementById('propertyForm').addEventListener('submit', function(e) {
            const requiredFields = this.querySelectorAll('[required]');
            let isValid = true;
            
            requiredFields.forEach(field => {
                if (!field.value.trim()) {
                    isValid = false;
                    field.classList.add('is-invalid');
                } else {
                    field.classList.remove('is-invalid');
                }
            });
            
            if (!isValid) {
                e.preventDefault();
                e.stopPropagation();
                alert('Please fill in all required fields.');
            }
        });
    </script>
</body>
</html>
