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

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

$tenant_id = $_GET['id'] ?? null;
$tenant = null;
$tenant_kyc = null;
$is_edit = false;

if ($tenant_id) {
    $is_edit = true;
    // Get user data
    $sql = "SELECT * FROM users WHERE id = ? AND role_id = 4";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $tenant_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $tenant = $result->fetch_assoc();
    
    if (!$tenant) {
        $_SESSION['error_message'] = "Tenant not found!";
        header('Location: list_tenants.php');
        exit();
    }
    
    // Get KYC data
    $kyc_sql = "SELECT * FROM tenant_kyc WHERE user_id = ?";
    $kyc_stmt = $conn->prepare($kyc_sql);
    $kyc_stmt->bind_param("i", $tenant_id);
    $kyc_stmt->execute();
    $kyc_result = $kyc_stmt->get_result();
    $tenant_kyc = $kyc_result->fetch_assoc();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // User table fields
    $first_name = trim($_POST['first_name']);
    $middle_name = trim($_POST['middle_name'] ?? '');
    $last_name = trim($_POST['last_name']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);
    $phone_secondary = trim($_POST['phone_secondary'] ?? '');
    $id_type = $_POST['id_type'] ?? 'National ID';
    $id_number = trim($_POST['id_number']);
    $dob = $_POST['dob'] ?? null;
    $gender = $_POST['gender'] ?? null;
    $nationality = trim($_POST['nationality'] ?? 'Kenyan');
    $address_postal = trim($_POST['address_postal'] ?? '');
    $city = trim($_POST['city'] ?? '');
    
    // KYC fields
    $kra_pin = trim($_POST['kra_pin'] ?? '');
    $occupation = trim($_POST['occupation'] ?? '');
    $employer_name = trim($_POST['employer_name'] ?? '');
    $employer_phone = trim($_POST['employer_phone'] ?? '');
    $employer_address = trim($_POST['employer_address'] ?? '');
    $monthly_income_range = $_POST['monthly_income_range'] ?? '';
    $nok_name = trim($_POST['nok_name'] ?? '');
    $nok_relation = trim($_POST['nok_relation'] ?? '');
    $nok_phone = trim($_POST['nok_phone'] ?? '');
    $has_pets = isset($_POST['has_pets']) ? 1 : 0;
    $pet_details = trim($_POST['pet_details'] ?? '');
    $car_reg_no = trim($_POST['car_reg_no'] ?? '');
    
    $conn->begin_transaction();
    
    try {
        if ($is_edit) {
            // Update user
            $sql = "UPDATE users SET 
                    first_name = ?, middle_name = ?, last_name = ?, email = ?, 
                    phone = ?, phone_secondary = ?, id_type = ?, id_number = ?, 
                    dob = ?, gender = ?, nationality = ?, address_postal = ?, 
                    city = ?, updated_at = NOW()
                    WHERE id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("sssssssssssssi", 
                $first_name, $middle_name, $last_name, $email, 
                $phone, $phone_secondary, $id_type, $id_number, 
                $dob, $gender, $nationality, $address_postal, 
                $city, $tenant_id
            );
            $stmt->execute();
            
            // Update or insert KYC
            if ($tenant_kyc) {
                $kyc_sql = "UPDATE tenant_kyc SET 
                           kra_pin = ?, occupation = ?, employer_name = ?, employer_phone = ?,
                           employer_address = ?, monthly_income_range = ?, nok_name = ?,
                           nok_relation = ?, nok_phone = ?, has_pets = ?, pet_details = ?,
                           car_reg_no = ?, updated_at = NOW()
                           WHERE user_id = ?";
                $kyc_stmt = $conn->prepare($kyc_sql);
                $kyc_stmt->bind_param("ssssssssssssi",
                    $kra_pin, $occupation, $employer_name, $employer_phone,
                    $employer_address, $monthly_income_range, $nok_name,
                    $nok_relation, $nok_phone, $has_pets, $pet_details,
                    $car_reg_no, $tenant_id
                );
            } else {
                $kyc_sql = "INSERT INTO tenant_kyc (
                           user_id, kra_pin, occupation, employer_name, employer_phone,
                           employer_address, monthly_income_range, nok_name, nok_relation,
                           nok_phone, has_pets, pet_details, car_reg_no
                           ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                $kyc_stmt = $conn->prepare($kyc_sql);
                $kyc_stmt->bind_param("issssssssssss",
                    $tenant_id, $kra_pin, $occupation, $employer_name, $employer_phone,
                    $employer_address, $monthly_income_range, $nok_name, $nok_relation,
                    $nok_phone, $has_pets, $pet_details, $car_reg_no
                );
            }
            $kyc_stmt->execute();
            
            $success_message = "Tenant updated successfully!";
        } else {
            // Default password (should be changed on first login)
            $default_password = password_hash('Password@123', PASSWORD_DEFAULT);
            
            // Insert user
            $sql = "INSERT INTO users (
                    role_id, first_name, middle_name, last_name, email, phone,
                    phone_secondary, id_type, id_number, dob, gender, nationality,
                    address_postal, city, password_hash, status, created_at
                    ) VALUES (4, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', NOW())";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("ssssssssssssss",
                $first_name, $middle_name, $last_name, $email, $phone,
                $phone_secondary, $id_type, $id_number, $dob, $gender,
                $nationality, $address_postal, $city, $default_password
            );
            $stmt->execute();
            $new_tenant_id = $conn->insert_id;
            
            // Insert KYC
            $kyc_sql = "INSERT INTO tenant_kyc (
                       user_id, kra_pin, occupation, employer_name, employer_phone,
                       employer_address, monthly_income_range, nok_name, nok_relation,
                       nok_phone, has_pets, pet_details, car_reg_no
                       ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $kyc_stmt = $conn->prepare($kyc_sql);
            $kyc_stmt->bind_param("issssssssssss",
                $new_tenant_id, $kra_pin, $occupation, $employer_name, $employer_phone,
                $employer_address, $monthly_income_range, $nok_name, $nok_relation,
                $nok_phone, $has_pets, $pet_details, $car_reg_no
            );
            $kyc_stmt->execute();
            
            $success_message = "Tenant added successfully! Default password: Password@123";
        }
        
        $conn->commit();
        $_SESSION['success_message'] = $success_message;
        header('Location: list_tenants.php');
        exit();
    } catch (Exception $e) {
        $conn->rollback();
        $error_message = "Error: " . $e->getMessage();
    }
}

$income_ranges = [
    'Below 50,000',
    '50,000 - 100,000',
    '100,000 - 150,000',
    '150,000 - 200,000',
    '200,000 - 300,000',
    'Above 300,000'
];
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => ($is_edit ? 'Edit' : 'Add') . ' Tenant')); ?>
    <?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;
        }
        .info-box {
            background: #f0f8ff;
            border-left: 3px solid #405189;
            padding: 12px;
            margin-bottom: 20px;
            border-radius: 4px;
        }
    </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' => 'Tenant Management', 
                        'title' => ($is_edit ? 'Edit' : 'Add') . ' Tenant'
                    )); ?>

                    <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-user-add-line fs-24 me-2"></i>
                                        </div>
                                        <div class="flex-grow-1">
                                            <h4 class="mb-0">
                                                <?php echo $is_edit ? 'Edit Tenant Details' : 'Add New Tenant'; ?>
                                            </h4>
                                            <p class="text-white-50 mb-0 mt-1" style="font-size: 13px;">
                                                <?php echo $is_edit ? 'Update tenant information and KYC details' : 'Fill in personal, contact, and employment information'; ?>
                                            </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; ?>

                                    <?php if (!$is_edit): ?>
                                    <div class="info-box">
                                        <i class="ri-information-line me-2"></i>
                                        <strong>Note:</strong> A default password (Password@123) will be assigned. The tenant should change it on first login.
                                    </div>
                                    <?php endif; ?>

                                    <form method="POST" id="tenantForm">
                                        <!-- Personal Information -->
                                        <div class="section-header">
                                            <h5><i class="ri-user-line me-2"></i>Personal Information</h5>
                                            <p>Basic identification and contact details</p>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">First Name 
                                                    <span class="required-badge">REQUIRED</span>
                                                </label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-user-3-line form-icon"></i>
                                                    <input type="text" class="form-control" name="first_name" 
                                                           value="<?php echo htmlspecialchars($tenant['first_name'] ?? ''); ?>" 
                                                           required placeholder="e.g., John">
                                                </div>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Middle Name 
                                                    <span class="badge bg-soft-info text-info">Optional</span>
                                                </label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-user-line form-icon"></i>
                                                    <input type="text" class="form-control" name="middle_name" 
                                                           value="<?php echo htmlspecialchars($tenant['middle_name'] ?? ''); ?>" 
                                                           placeholder="e.g., Michael">
                                                </div>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Last Name 
                                                    <span class="required-badge">REQUIRED</span>
                                                </label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-user-4-line form-icon"></i>
                                                    <input type="text" class="form-control" name="last_name" 
                                                           value="<?php echo htmlspecialchars($tenant['last_name'] ?? ''); ?>" 
                                                           required placeholder="e.g., Doe">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-3 mb-3">
                                                <label class="form-label">Gender</label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-genderless-line form-icon"></i>
                                                    <select class="form-select select2" name="gender">
                                                        <option value="">Select Gender</option>
                                                        <option value="Male" <?php echo ($tenant['gender'] ?? '') == 'Male' ? 'selected' : ''; ?>>Male</option>
                                                        <option value="Female" <?php echo ($tenant['gender'] ?? '') == 'Female' ? 'selected' : ''; ?>>Female</option>
                                                        <option value="Other" <?php echo ($tenant['gender'] ?? '') == 'Other' ? 'selected' : ''; ?>>Other</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="col-md-3 mb-3">
                                                <label class="form-label">Date of Birth</label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-calendar-line form-icon"></i>
                                                    <input type="date" class="form-control" name="dob" 
                                                           value="<?php echo $tenant['dob'] ?? ''; ?>">
                                                </div>
                                            </div>
                                            <div class="col-md-3 mb-3">
                                                <label class="form-label">Nationality</label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-flag-line form-icon"></i>
                                                    <input type="text" class="form-control" name="nationality" 
                                                           value="<?php echo htmlspecialchars($tenant['nationality'] ?? 'Kenyan'); ?>" 
                                                           placeholder="e.g., Kenyan">
                                                </div>
                                            </div>
                                            <div class="col-md-3 mb-3">
                                                <label class="form-label">ID Type 
                                                    <span class="required-badge">REQUIRED</span>
                                                </label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-bank-card-line form-icon"></i>
                                                    <select class="form-select select2" name="id_type" required>
                                                        <option value="National ID" <?php echo ($tenant['id_type'] ?? 'National ID') == 'National ID' ? 'selected' : ''; ?>>National ID</option>
                                                        <option value="Passport" <?php echo ($tenant['id_type'] ?? '') == 'Passport' ? 'selected' : ''; ?>>Passport</option>
                                                        <option value="Alien ID" <?php echo ($tenant['id_type'] ?? '') == 'Alien ID' ? 'selected' : ''; ?>>Alien ID</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">ID Number 
                                                    <span class="required-badge">REQUIRED</span>
                                                </label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-profile-line form-icon"></i>
                                                    <input type="text" class="form-control" name="id_number" 
                                                           value="<?php echo htmlspecialchars($tenant['id_number'] ?? ''); ?>" 
                                                           required placeholder="e.g., 12345678">
                                                </div>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">KRA PIN</label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-file-list-3-line form-icon"></i>
                                                    <input type="text" class="form-control" name="kra_pin" 
                                                           value="<?php echo htmlspecialchars($tenant_kyc['kra_pin'] ?? ''); ?>" 
                                                           placeholder="e.g., A001234567P">
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Contact Information -->
                                        <div class="section-header">
                                            <h5><i class="ri-phone-line me-2"></i>Contact Information</h5>
                                            <p>Email, phone, and address details</p>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Email 
                                                    <span class="required-badge">REQUIRED</span>
                                                </label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-mail-line form-icon"></i>
                                                    <input type="email" class="form-control" name="email" 
                                                           value="<?php echo htmlspecialchars($tenant['email'] ?? ''); ?>" 
                                                           required placeholder="e.g., john.doe@email.com">
                                                </div>
                                            </div>
                                            <div class="col-md-3 mb-3">
                                                <label class="form-label">Primary Phone 
                                                    <span class="required-badge">REQUIRED</span>
                                                </label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-smartphone-line form-icon"></i>
                                                    <input type="tel" class="form-control" name="phone" 
                                                           value="<?php echo htmlspecialchars($tenant['phone'] ?? ''); ?>" 
                                                           required placeholder="+254712345678">
                                                </div>
                                            </div>
                                            <div class="col-md-3 mb-3">
                                                <label class="form-label">Secondary Phone 
                                                    <span class="badge bg-soft-info text-info">Optional</span>
                                                </label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-phone-fill form-icon"></i>
                                                    <input type="tel" class="form-control" name="phone_secondary" 
                                                           value="<?php echo htmlspecialchars($tenant['phone_secondary'] ?? ''); ?>" 
                                                           placeholder="+254723456789">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-8 mb-3">
                                                <label class="form-label">Postal Address</label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-map-pin-line form-icon"></i>
                                                    <input type="text" class="form-control" name="address_postal" 
                                                           value="<?php echo htmlspecialchars($tenant['address_postal'] ?? ''); ?>" 
                                                           placeholder="e.g., P.O. Box 12345-00100">
                                                </div>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">City</label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-building-line form-icon"></i>
                                                    <input type="text" class="form-control" name="city" 
                                                           value="<?php echo htmlspecialchars($tenant['city'] ?? ''); ?>" 
                                                           placeholder="e.g., Nairobi">
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Employment Information -->
                                        <div class="section-header">
                                            <h5><i class="ri-briefcase-line me-2"></i>Employment Information</h5>
                                            <p>Occupation and employer details</p>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Occupation</label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-briefcase-4-line form-icon"></i>
                                                    <input type="text" class="form-control" name="occupation" 
                                                           value="<?php echo htmlspecialchars($tenant_kyc['occupation'] ?? ''); ?>" 
                                                           placeholder="e.g., Software Engineer">
                                                </div>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Monthly Income Range</label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-money-dollar-circle-line form-icon"></i>
                                                    <select class="form-select select2" name="monthly_income_range">
                                                        <option value="">Select Range</option>
                                                        <?php foreach($income_ranges as $range): ?>
                                                            <option value="<?php echo $range; ?>" 
                                                                    <?php echo ($tenant_kyc['monthly_income_range'] ?? '') == $range ? 'selected' : ''; ?>>
                                                                KES <?php echo $range; ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Employer Name</label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-building-2-line form-icon"></i>
                                                    <input type="text" class="form-control" name="employer_name" 
                                                           value="<?php echo htmlspecialchars($tenant_kyc['employer_name'] ?? ''); ?>" 
                                                           placeholder="e.g., ABC Company Ltd">
                                                </div>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Employer Phone</label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-phone-line form-icon"></i>
                                                    <input type="tel" class="form-control" name="employer_phone" 
                                                           value="<?php echo htmlspecialchars($tenant_kyc['employer_phone'] ?? ''); ?>" 
                                                           placeholder="+254712345678">
                                                </div>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Employer Address</label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-map-2-line form-icon"></i>
                                                    <input type="text" class="form-control" name="employer_address" 
                                                           value="<?php echo htmlspecialchars($tenant_kyc['employer_address'] ?? ''); ?>" 
                                                           placeholder="e.g., Westlands, Nairobi">
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Emergency Contact -->
                                        <div class="section-header">
                                            <h5><i class="ri-user-heart-line me-2"></i>Emergency Contact (Next of Kin)</h5>
                                            <p>Contact person in case of emergency</p>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Name</label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-user-2-line form-icon"></i>
                                                    <input type="text" class="form-control" name="nok_name" 
                                                           value="<?php echo htmlspecialchars($tenant_kyc['nok_name'] ?? ''); ?>" 
                                                           placeholder="e.g., Jane Doe">
                                                </div>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Relationship</label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-parent-line form-icon"></i>
                                                    <input type="text" class="form-control" name="nok_relation" 
                                                           value="<?php echo htmlspecialchars($tenant_kyc['nok_relation'] ?? ''); ?>" 
                                                           placeholder="e.g., Mother, Brother">
                                                </div>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Phone Number</label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-contacts-line form-icon"></i>
                                                    <input type="tel" class="form-control" name="nok_phone" 
                                                           value="<?php echo htmlspecialchars($tenant_kyc['nok_phone'] ?? ''); ?>" 
                                                           placeholder="+254712345678">
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Additional Details -->
                                        <div class="section-header">
                                            <h5><i class="ri-more-2-line me-2"></i>Additional Details</h5>
                                            <p>Vehicle and pet information</p>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Vehicle Registration Number</label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-car-line form-icon"></i>
                                                    <input type="text" class="form-control" name="car_reg_no" 
                                                           value="<?php echo htmlspecialchars($tenant_kyc['car_reg_no'] ?? ''); ?>" 
                                                           placeholder="e.g., KBZ 123A">
                                                </div>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Pet Information</label>
                                                <div class="mb-2">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox" name="has_pets" 
                                                               id="has_pets" <?php echo ($tenant_kyc['has_pets'] ?? 0) ? 'checked' : ''; ?>>
                                                        <label class="form-check-label" for="has_pets">
                                                            <i class="ri-bear-smile-line me-1"></i>Tenant has pets
                                                        </label>
                                                    </div>
                                                </div>
                                                <input type="text" class="form-control" name="pet_details" 
                                                       value="<?php echo htmlspecialchars($tenant_kyc['pet_details'] ?? ''); ?>" 
                                                       placeholder="e.g., 1 Dog - German Shepherd">
                                            </div>
                                        </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 Tenant' : 'Add Tenant'; ?>
                                            </button>
                                            <a href="list_tenants.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
            $('.select2').select2({
                theme: 'bootstrap-5',
                width: '100%'
            });
            
            // Form validation
            $('#tenantForm').on('submit', function(e) {
                let isValid = true;
                
                $(this).find('[required]').each(function() {
                    if (!$(this).val()) {
                        isValid = false;
                        $(this).addClass('is-invalid');
                    } else {
                        $(this).removeClass('is-invalid');
                    }
                });
                
                if (!isValid) {
                    e.preventDefault();
                    $('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>