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

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

$tenant_id = $_GET['tenant_id'] ?? null;
$tenant = null;

if ($tenant_id) {
    // Get tenant details
    $sql = "SELECT id, CONCAT(first_name, ' ', last_name) as full_name, email, phone 
            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();
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $tenant_id = $_POST['tenant_id'];
    $unit_id = $_POST['unit_id'];
    $start_date = $_POST['start_date'];
    $end_date = $_POST['end_date'];
    $move_in_date = $_POST['move_in_date'] ?? $start_date;
    $rent_amount = $_POST['rent_amount'];
    $deposit_amount = $_POST['deposit_amount'];
    $service_charge = $_POST['service_charge'] ?? 0;
    $water_deposit = $_POST['water_deposit'] ?? 0;
    $electricity_deposit = $_POST['electricity_deposit'] ?? 0;
    $payment_frequency = $_POST['payment_frequency'] ?? 'monthly';
    $due_day = $_POST['due_day'] ?? 5;
    $grace_period_days = $_POST['grace_period_days'] ?? 5;
    $late_fee_type = $_POST['late_fee_type'] ?? 'Fixed';
    $late_fee_value = $_POST['late_fee_value'] ?? 0;
    $escalation_rate_percent = $_POST['escalation_rate_percent'] ?? 0;
    
    $conn->begin_transaction();
    
    try {
        // Insert lease
        $sql = "INSERT INTO leases (
                    unit_id, tenant_id, start_date, end_date, move_in_date,
                    rent_amount, deposit_amount, service_charge, water_deposit,
                    electricity_deposit, payment_frequency, due_day, grace_period_days,
                    late_fee_type, late_fee_value, escalation_rate_percent, status, created_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', NOW())";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("iisssdddddsiisd",
            $unit_id, $tenant_id, $start_date, $end_date, $move_in_date,
            $rent_amount, $deposit_amount, $service_charge, $water_deposit,
            $electricity_deposit, $payment_frequency, $due_day, $grace_period_days,
            $late_fee_type, $late_fee_value, $escalation_rate_percent
        );
        $stmt->execute();
        $lease_id = $conn->insert_id;
        
        // Update unit status to occupied
        $update_sql = "UPDATE units SET status = 'occupied' WHERE id = ?";
        $update_stmt = $conn->prepare($update_sql);
        $update_stmt->bind_param("i", $unit_id);
        $update_stmt->execute();
        
        // Create security deposit record
        if ($deposit_amount > 0) {
            $deposit_sql = "INSERT INTO security_deposits (
                               lease_id, tenant_id, unit_id, deposit_type,
                               amount_collected, collection_date, status, created_at
                           ) VALUES (?, ?, ?, 'Security', ?, ?, 'held', NOW())";
            $deposit_stmt = $conn->prepare($deposit_sql);
            $deposit_stmt->bind_param("iiids", $lease_id, $tenant_id, $unit_id, $deposit_amount, $start_date);
            $deposit_stmt->execute();
        }
        
        $conn->commit();
        $_SESSION['success_message'] = "Lease created successfully!";
        header('Location: tenant_details.php?id=' . $tenant_id);
        exit();
    } catch (Exception $e) {
        $conn->rollback();
        $error_message = "Error: " . $e->getMessage();
    }
}

// Get properties for dropdown
$properties_sql = "SELECT id, name, location_area FROM properties ORDER BY name";
$properties_result = $conn->query($properties_sql);
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Create Lease')); ?>
    <?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;
        }
        .tenant-info-box {
            background: linear-gradient(135deg, #f0f8ff 0%, #e8f4f8 100%);
            border-left: 4px solid #405189;
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .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' => 'Lease Management', 
                        'title' => 'Create New Lease'
                    )); ?>

                    <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-file-add-line fs-24 me-2"></i>
                                        </div>
                                        <div class="flex-grow-1">
                                            <h4 class="mb-0">Create New Lease Agreement</h4>
                                            <p class="text-white-50 mb-0 mt-1" style="font-size: 13px;">
                                                Set up lease terms, rent amount, deposits, and payment schedule
                                            </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 ($tenant): ?>
                                    <div class="tenant-info-box">
                                        <div class="d-flex align-items-center">
                                            <i class="ri-user-3-line fs-24 text-primary me-3"></i>
                                            <div>
                                                <h6 class="mb-1">Creating lease for:</h6>
                                                <p class="mb-0">
                                                    <strong><?php echo htmlspecialchars($tenant['full_name']); ?></strong>
                                                    <span class="text-muted mx-2">|</span>
                                                    <i class="ri-mail-line me-1"></i><?php echo htmlspecialchars($tenant['email']); ?>
                                                    <span class="text-muted mx-2">|</span>
                                                    <i class="ri-phone-line me-1"></i><?php echo htmlspecialchars($tenant['phone']); ?>
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endif; ?>

                                    <form method="POST" id="leaseForm">
                                        <!-- Tenant Selection -->
                                        <div class="section-header">
                                            <h5><i class="ri-user-line me-2"></i>Tenant Information</h5>
                                            <p>Select the tenant for this lease</p>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-12 mb-3">
                                                <label class="form-label">Tenant 
                                                    <span class="required-badge">REQUIRED</span>
                                                </label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-user-3-line form-icon"></i>
                                                    <select class="form-select select2" name="tenant_id" required>
                                                        <option value="">Select Tenant</option>
                                                        <?php
                                                        $tenants_sql = "SELECT id, CONCAT(first_name, ' ', last_name, ' - ', email) as tenant_info 
                                                                       FROM users WHERE role_id = 4 AND status = 'active' ORDER BY first_name";
                                                        $tenants_result = $conn->query($tenants_sql);
                                                        while($t = $tenants_result->fetch_assoc()):
                                                        ?>
                                                            <option value="<?php echo $t['id']; ?>" 
                                                                    <?php echo ($tenant && $t['id'] == $tenant['id']) ? 'selected' : ''; ?>>
                                                                <?php echo htmlspecialchars($t['tenant_info']); ?>
                                                            </option>
                                                        <?php endwhile; ?>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Property & Unit Selection -->
                                        <div class="section-header">
                                            <h5><i class="ri-home-4-line me-2"></i>Property & Unit</h5>
                                            <p>Select property and available unit</p>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Property 
                                                    <span class="required-badge">REQUIRED</span>
                                                </label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-building-line form-icon"></i>
                                                    <select class="form-select select2" id="property_id" required>
                                                        <option value="">Select Property</option>
                                                        <?php while($property = $properties_result->fetch_assoc()): ?>
                                                            <option value="<?php echo $property['id']; ?>">
                                                                <?php echo htmlspecialchars($property['name'] . ' - ' . $property['location_area']); ?>
                                                            </option>
                                                        <?php endwhile; ?>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Unit 
                                                    <span class="required-badge">REQUIRED</span>
                                                </label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-home-3-line form-icon"></i>
                                                    <select class="form-select select2" name="unit_id" id="unit_id" required>
                                                        <option value="">Select Property First</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Lease Period -->
                                        <div class="section-header">
                                            <h5><i class="ri-calendar-line me-2"></i>Lease Period</h5>
                                            <p>Set the duration and dates for this lease</p>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Start Date 
                                                    <span class="required-badge">REQUIRED</span>
                                                </label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-calendar-check-line form-icon"></i>
                                                    <input type="date" class="form-control" name="start_date" required>
                                                </div>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">End Date 
                                                    <span class="required-badge">REQUIRED</span>
                                                </label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-calendar-close-line form-icon"></i>
                                                    <input type="date" class="form-control" name="end_date" required>
                                                </div>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Move-in Date 
                                                    <span class="badge bg-soft-info text-info">Optional</span>
                                                </label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-door-open-line form-icon"></i>
                                                    <input type="date" class="form-control" name="move_in_date">
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Rent & Charges -->
                                        <div class="section-header">
                                            <h5><i class="ri-money-dollar-circle-line me-2"></i>Rent & Charges</h5>
                                            <p>Set monthly rent and additional charges</p>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Monthly Rent 
                                                    <span class="required-badge">REQUIRED</span>
                                                </label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-money-dollar-box-line form-icon"></i>
                                                    <input type="number" step="0.01" class="form-control" name="rent_amount" 
                                                           id="rent_amount" placeholder="0.00" required>
                                                </div>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Service Charge</label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-service-line form-icon"></i>
                                                    <input type="number" step="0.01" class="form-control" name="service_charge" 
                                                           placeholder="0.00">
                                                </div>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Payment Frequency</label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-calendar-event-line form-icon"></i>
                                                    <select class="form-select select2" name="payment_frequency">
                                                        <option value="monthly" selected>Monthly</option>
                                                        <option value="quarterly">Quarterly</option>
                                                        <option value="yearly">Yearly</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Deposits -->
                                        <div class="section-header">
                                            <h5><i class="ri-wallet-3-line me-2"></i>Deposits</h5>
                                            <p>Security and utility deposits</p>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Security Deposit 
                                                    <span class="required-badge">REQUIRED</span>
                                                </label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-shield-check-line form-icon"></i>
                                                    <input type="number" step="0.01" class="form-control" name="deposit_amount" 
                                                           placeholder="0.00" required>
                                                </div>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Water Deposit</label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-drop-line form-icon"></i>
                                                    <input type="number" step="0.01" class="form-control" name="water_deposit" 
                                                           placeholder="0.00">
                                                </div>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Electricity Deposit</label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-flashlight-line form-icon"></i>
                                                    <input type="number" step="0.01" class="form-control" name="electricity_deposit" 
                                                           placeholder="0.00">
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Payment Terms -->
                                        <div class="section-header">
                                            <h5><i class="ri-calendar-todo-line me-2"></i>Payment Terms</h5>
                                            <p>Set due date, grace period, and late fees</p>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Due Day of Month</label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-calendar-2-line form-icon"></i>
                                                    <input type="number" class="form-control" name="due_day" 
                                                           value="5" min="1" max="31" placeholder="5">
                                                </div>
                                                <small class="text-muted">Day when rent is due (e.g., 5th of each month)</small>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Grace Period (Days)</label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-time-line form-icon"></i>
                                                    <input type="number" class="form-control" name="grace_period_days" 
                                                           value="5" min="0" placeholder="5">
                                                </div>
                                                <small class="text-muted">Days before late fee applies</small>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Escalation Rate (%)</label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-arrow-up-line form-icon"></i>
                                                    <input type="number" step="0.01" class="form-control" name="escalation_rate_percent" 
                                                           value="0" placeholder="0.00">
                                                </div>
                                                <small class="text-muted">Yearly rent increase percentage</small>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Late Fee Type</label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-error-warning-line form-icon"></i>
                                                    <select class="form-select select2" name="late_fee_type">
                                                        <option value="Fixed" selected>Fixed Amount</option>
                                                        <option value="Percentage">Percentage of Rent</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Late Fee Value</label>
                                                <div class="icon-input-wrapper">
                                                    <i class="ri-money-dollar-circle-line form-icon"></i>
                                                    <input type="number" step="0.01" class="form-control" name="late_fee_value" 
                                                           placeholder="0.00">
                                                </div>
                                                <small class="text-muted">Amount or percentage to charge after grace period</small>
                                            </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>
                                                Create Lease
                                            </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%'
            });
            
            // Load units when property is selected
            $('#property_id').on('change', function() {
                const propertyId = $(this).val();
                const unitSelect = $('#unit_id');
                
                if (propertyId) {
                    $.ajax({
                        url: 'ajax/get_units.php',
                        method: 'POST',
                        data: { property_id: propertyId },
                        dataType: 'json',
                        success: function(response) {
                            unitSelect.empty();
                            unitSelect.append('<option value="">Select Unit</option>');
                            
                            if (response.success && response.units.length > 0) {
                                response.units.forEach(function(unit) {
                                    unitSelect.append(
                                        `<option value="${unit.id}" data-rent="${unit.rent_amount}">
                                            Unit ${unit.unit_number} - ${unit.bedrooms}BR - KES ${parseFloat(unit.rent_amount).toLocaleString()}
                                        </option>`
                                    );
                                });
                            } else {
                                unitSelect.append('<option value="">No vacant units available</option>');
                            }
                            
                            unitSelect.trigger('change');
                        },
                        error: function() {
                            unitSelect.empty();
                            unitSelect.append('<option value="">Error loading units</option>');
                        }
                    });
                } else {
                    unitSelect.empty();
                    unitSelect.append('<option value="">Select Property First</option>');
                }
            });
            
            // Auto-fill rent amount when unit is selected
            $('#unit_id').on('change', function() {
                const selectedOption = $(this).find('option:selected');
                const rentAmount = selectedOption.data('rent');
                
                if (rentAmount) {
                    $('#rent_amount').val(rentAmount);
                }
            });
            
            // Form validation
            $('#leaseForm').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');
                    }
                });
                
                // Validate dates
                const startDate = new Date($('[name="start_date"]').val());
                const endDate = new Date($('[name="end_date"]').val());
                
                if (endDate <= startDate) {
                    alert('End date must be after start date');
                    isValid = false;
                }
                
                if (!isValid) {
                    e.preventDefault();
                    $('html, body').animate({
                        scrollTop: $('.is-invalid').first().offset().top - 100
                    }, 500);
                }
            });
            
            // Remove invalid class on input
            $('input, select').on('change keyup', function() {
                if ($(this).val()) {
                    $(this).removeClass('is-invalid');
                }
            });
        });
    </script>
</body>
</html>