<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// Start session and check if user is logged in
session_start();
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
    header("location: login.php");
    exit;
}

// Include config file
require_once "includes/config.php";

// Initialize variables
$error = "";
$success = "";
$name = $description = "";

// Handle form submission for adding property type
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
    $name = trim($_POST['name']);
    $description = trim($_POST['description']);
    $type_id = !empty($_POST['type_id']) ? (int)$_POST['type_id'] : 0;
    
    if (empty($name)) {
        $error = "Please enter a property type name.";
    } else {
        try {
            if ($type_id > 0) {
                $sql = "UPDATE property_types SET name = ?, description = ? WHERE id = ?";
            } else {
                $sql = "INSERT INTO property_types (name, description) VALUES (?, ?)";
            }
            
            if ($stmt = $conn->prepare($sql)) {
                if ($type_id > 0) {
                    $stmt->bind_param("ssi", $name, $description, $type_id);
                } else {
                    $stmt->bind_param("ss", $name, $description);
                }
                
                if ($stmt->execute()) {
                    header("Location: " . $_SERVER['PHP_SELF']);
                    exit;
                } else {
                    $error = "Error: " . $stmt->error;
                }
                $stmt->close();
            }
        } catch (Exception $e) {
            $error = "Error: " . $e->getMessage();
        }
    }
}

// Handle deletion
if (isset($_POST['delete_id'])) {
    $type_id = (int)$_POST['delete_id'];

    try {
        $check_sql = "SELECT COUNT(*) FROM properties WHERE property_type_id = ?";
        $check_stmt = $conn->prepare($check_sql);
        $check_stmt->bind_param("i", $type_id);
        $check_stmt->execute();
        $check_stmt->bind_result($count);
        $check_stmt->fetch();
        $check_stmt->close();

        if ($count > 0) {
            $error = "Cannot delete: There are properties using this type.";
        } else {
            $delete_sql = "DELETE FROM property_types WHERE id = ?";
            $delete_stmt = $conn->prepare($delete_sql);
            $delete_stmt->bind_param("i", $type_id);
            $delete_stmt->execute();
            $delete_stmt->close();

            header("Location: " . $_SERVER['PHP_SELF']);
            exit;
        }
    } catch (Exception $e) {
        $error = "Error: " . $e->getMessage();
    }
}

// ✅ FIXED FETCH PART (NO fetch_all)
$property_types = [];
$all_property_types = [];

try {
    $sql = "SELECT * FROM property_types ORDER BY name ASC";
    $result = $conn->query($sql);

    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $property_types[] = $row;
            $all_property_types[] = $row;
        }
        $result->free();
    }
} catch (Exception $e) {
    $error = "Error fetching property types: " . $e->getMessage();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Property Types - Admin Panel</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>
        :root {
            --primary-color: #4361ee;
            --secondary-color: #3f37c9;
            --light-color: #f8f9fa;
            --dark-color: #212529;
        }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f5f7fb;
            color: #333;
        }
        .sidebar {
            min-height: 100vh;
            background: linear-gradient(180deg, var(--primary-color), var(--secondary-color));
            color: white;
            padding: 1.5rem 0;
            position: fixed;
            width: 250px;
        }
        .sidebar-brand {
            padding: 0 1.5rem 1.5rem;
            text-align: center;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            margin-bottom: 1rem;
        }
        .sidebar-brand h3 {
            color: white;
            margin: 0;
            font-weight: 700;
            font-size: 1.5rem;
        }
        .nav-link {
            color: rgba(255, 255, 255, 0.8);
            padding: 0.75rem 1.5rem;
            margin: 0.25rem 0.5rem;
            border-radius: 8px;
            display: flex;
            align-items: center;
            transition: all 0.3s;
        }
        .nav-link i {
            margin-right: 10px;
            width: 20px;
            text-align: center;
        }
        .nav-link:hover, .nav-link.active {
            background-color: rgba(255, 255, 255, 0.1);
            color: white;
            text-decoration: none;
        }
        .main-content {
            margin-left: 250px;
            padding: 2rem;
        }
        .card {
            border: none;
            border-radius: 10px;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
            margin-bottom: 1.5rem;
        }
        .card-header {
            background-color: #fff;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
            font-weight: 600;
            padding: 1rem 1.5rem;
        }
        .table th {
            font-weight: 600;
        }
    </style>
</head>
<body>
    <div class="d-flex">
        <!-- Sidebar -->
        <div class="sidebar">
            <div class="sidebar-brand">
                <h3>Admin Panel</h3>
            </div>
            <ul class="nav flex-column">
                <li class="nav-item">
                    <a class="nav-link" href="index.php">
                        <i class="fas fa-tachometer-alt"></i> Dashboard
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link active" href="property-add.php">
                        <i class="fas fa-home"></i> Property Types
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="properties.php">
                        <i class="fas fa-building"></i> Properties
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="categories.php">
                        <i class="fas fa-tags"></i> Categories
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="gallery-upload.php">
                        <i class="fas fa-images"></i> Gallery
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="profile.php">
                        <i class="fas fa-user"></i> Profile
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="logout.php">
                        <i class="fas fa-sign-out-alt"></i> Logout
                    </a>
                </li>
            </ul>
        </div>
        
        <!-- Main Content -->
        <div class="main-content w-100">
            <div class="container-fluid">
                <!-- Page Header -->
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h1 class="h3 mb-0">Manage Property Types</h1>
                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#propertyTypeModal">
                        <i class="fas fa-plus me-2"></i> Add New Property Type
                    </button>
                </div>
                
                <?php if ($error): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <?php echo $error; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>
                
                <?php if ($success): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <?php echo $success; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>
                
                <!-- Property Types Table -->
                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-list me-2"></i> Property Types
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-hover mb-0">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Name</th>
                                        <th>Description</th>
                                        <th>Created</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (empty($property_types)): ?>
                                        <tr>
                                            <td colspan="5" class="text-center py-4">No property types found. Add your first one!</td>
                                        </tr>
                                    <?php else: ?>
                                        <?php foreach ($property_types as $type): ?>
                                            <tr>
                                                <td><?php echo $type['id']; ?></td>
                                                <td><?php echo htmlspecialchars($type['name']); ?></td>
                                                <td><?php echo !empty($type['description']) ? htmlspecialchars($type['description']) : '—'; ?></td>
                                                <td><?php echo date('M d, Y', strtotime($type['created_at'])); ?></td>
                                                <td>
                                                    <button class="btn btn-sm btn-outline-primary edit-type" 
                                                            data-id="<?php echo $type['id']; ?>"
                                                            data-name="<?php echo htmlspecialchars($type['name']); ?>"
                                                            data-description="<?php echo htmlspecialchars($type['description']); ?>">
                                                        <i class="fas fa-edit"></i> Edit
                                                    </button>
                                                    <form method="post" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this property type?');">
                                                        <input type="hidden" name="delete_id" value="<?php echo $type['id']; ?>">
                                                        <button type="submit" class="btn btn-sm btn-outline-danger">
                                                            <i class="fas fa-trash"></i> Delete
                                                        </button>
                                                    </form>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Add/Edit Property Type Modal -->
    <div class="modal fade" id="propertyTypeModal" tabindex="-1" aria-labelledby="propertyTypeModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form id="propertyTypeForm" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
                    <input type="hidden" name="type_id" id="type_id" value="">
                    <div class="modal-header">
                        <h5 class="modal-title" id="propertyTypeModalLabel">Add New Property Type</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="name" class="form-label">Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="name" name="name" required 
                                   value="<?php echo isset($name) ? htmlspecialchars($name) : ''; ?>">
                        </div>
                        <div class="mb-3">
                            <label for="property_type" class="form-label">Property Type</label>
                            <select class="form-select" id="property_type" name="property_type">
                                <option value="">-- Select Property Type --</option>
                                <?php foreach ($all_property_types as $type): ?>
                                    <option value="<?php echo $type['id']; ?>" 
                                        <?php echo (isset($property_type_id) && $property_type_id == $type['id']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($type['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="description" class="form-label">Description</label>
                            <textarea class="form-control" id="description" name="description" rows="3"><?php 
                                echo isset($description) ? htmlspecialchars($description) : ''; 
                            ?></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" name="submit" class="btn btn-primary">Save Property Type</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // Function to handle edit button click
        function setupEditButtons() {
            document.querySelectorAll('.edit-type').forEach(button => {
                // Remove any existing event listeners to prevent duplicates
                button.removeEventListener('click', handleEditClick);
                button.addEventListener('click', handleEditClick);
            });
        }

        // Handle edit button click
        function handleEditClick(e) {
            e.preventDefault();
            const id = this.getAttribute('data-id');
            const name = this.getAttribute('data-name');
            const description = this.getAttribute('data-description') || '';
            
            // Set the form values
            document.getElementById('type_id').value = id;
            document.getElementById('name').value = name;
            document.getElementById('description').value = description;
            document.getElementById('propertyTypeModalLabel').textContent = 'Edit Property Type';
            
            // Show the modal
            const modal = new bootstrap.Modal(document.getElementById('propertyTypeModal'));
            modal.show();
        }

        // Initialize when document is ready
        document.addEventListener('DOMContentLoaded', function() {
            // Setup edit buttons
            setupEditButtons();
            
            // Reset form when modal is hidden
            const modal = document.getElementById('propertyTypeModal');
            if (modal) {
                modal.addEventListener('hidden.bs.modal', function () {
                    const form = document.getElementById('propertyTypeForm');
                    if (form) {
                        form.reset();
                        document.getElementById('type_id').value = '';
                        document.getElementById('propertyTypeModalLabel').textContent = 'Add New Property Type';
                    }
                });
            }

            // Add click handler for the Add New button
            const addNewBtn = document.querySelector('[data-bs-target="#propertyTypeModal"]');
            if (addNewBtn) {
                addNewBtn.addEventListener('click', function() {
                    document.getElementById('propertyTypeModalLabel').textContent = 'Add New Property Type';
                    document.getElementById('type_id').value = '';
                });
            }
        });
    </script>
</body>
</html>