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

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

$user_id = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $property_id = $_POST['property_id'];
    $unit_id = $_POST['unit_id'] ?? null;
    $category = $_POST['category'];
    $priority = $_POST['priority'] ?? 'Medium';
    $subject = $_POST['subject'];
    $description = $_POST['description'];
    
    // Generate ticket number
    $ticket_number = 'MR-' . date('Ymd') . '-' . strtoupper(substr(uniqid(), -6));
    
    // Get tenant_id from user_id
    $sql_tenant = "SELECT tenant_id FROM tenants WHERE user_id = ?";
    $stmt_tenant = $conn->prepare($sql_tenant);
    $stmt_tenant->bind_param("i", $user_id);
    $stmt_tenant->execute();
    $result_tenant = $stmt_tenant->get_result();
    $tenant = $result_tenant->fetch_assoc();
    
    if ($tenant) {
        $sql = "INSERT INTO maintenance_requests (ticket_number, property_id, unit_id, tenant_id, 
                                                  category, priority, subject, description, status, created_at) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'Open', NOW())";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("siiissss", $ticket_number, $property_id, $unit_id, $tenant['tenant_id'], 
                         $category, $priority, $subject, $description);
        
        if ($stmt->execute()) {
            $_SESSION['success_message'] = "Maintenance request submitted successfully! Ticket: " . $ticket_number;
            header('Location: my_maintenance_requests.php');
            exit();
        } else {
            $error_message = "Error: " . $conn->error;
        }
    } else {
        $error_message = "Tenant profile not found";
    }
}

// Get tenant's property/unit
$sql_lease = "SELECT DISTINCT p.id as property_id, p.name as property_name, u.id as unit_id, u.unit_number
              FROM leases l
              JOIN units u ON l.unit_id = u.id
              JOIN properties p ON u.property_id = p.id
              JOIN lease_tenants lt ON l.id = lt.lease_id AND lt.is_primary = 1
              WHERE lt.tenant_id = (SELECT tenant_id FROM tenants WHERE user_id = ?)
              AND l.status = 'active'";

$stmt = $conn->prepare($sql_lease);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Report Issue')); ?>
    <?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' => 'Maintenance', 'title' => 'Report Maintenance Issue')); ?>

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Submit Maintenance Request</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">
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Property/Unit <span class="text-danger">*</span></label>
                                                <select class="form-select" name="property_id" required>
                                                    <option value="">Select Property/Unit</option>
                                                    <?php while($lease = $result->fetch_assoc()): ?>
                                                        <option value="<?php echo $lease['property_id']; ?>" 
                                                                data-unit="<?php echo $lease['unit_id']; ?>">
                                                            <?php echo htmlspecialchars($lease['property_name'] . ' - Unit ' . $lease['unit_number']); ?>
                                                        </option>
                                                    <?php endwhile; ?>
                                                </select>
                                                <input type="hidden" name="unit_id" id="unit_id">
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Category <span class="text-danger">*</span></label>
                                                <select class="form-select" name="category" required>
                                                    <option value="">Select Category</option>
                                                    <option value="PLUMBING">Plumbing</option>
                                                    <option value="ELECTRICAL">Electrical</option>
                                                    <option value="HVAC">HVAC</option>
                                                    <option value="APPLIANCE">Appliance</option>
                                                    <option value="STRUCTURAL">Structural</option>
                                                    <option value="PEST">Pest Control</option>
                                                    <option value="OTHER">Other</option>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Priority</label>
                                                <select class="form-select" name="priority">
                                                    <option value="Low">Low</option>
                                                    <option value="Medium" selected>Medium</option>
                                                    <option value="High">High</option>
                                                    <option value="Emergency">Emergency</option>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">Subject <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control" name="subject" 
                                                   placeholder="Brief description of the issue" required>
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">Description <span class="text-danger">*</span></label>
                                            <textarea class="form-control" name="description" rows="5" 
                                                      placeholder="Detailed description of the maintenance issue..." required></textarea>
                                        </div>

                                        <div class="mt-4">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="ri-send-plane-line align-bottom me-1"></i>Submit Request
                                            </button>
                                            <a href="my_maintenance_requests.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.querySelector('select[name="property_id"]').addEventListener('change', function() {
            const selectedOption = this.options[this.selectedIndex];
            document.getElementById('unit_id').value = selectedOption.dataset.unit || '';
        });
    </script>
</body>
</html>
