<?php
/**
 * ============================================================================
 * admin/create-buyer.php - Create Buyer Account
 * ============================================================================
 * Admin-side creation of buyers (companies, cooperatives, first-tier buyers)
 */

require_once __DIR__ . '/includes/base.php';

$breadcrumbs = [
    ['title' => 'Create Buyer', 'url' => '']
];

renderAdminHeader('Create Buyer Account', $breadcrumbs);
?>

<div class="row justify-content-center">
    <div class="col-lg-8">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-success text-white py-3">
                <h5 class="mb-0">
                    <i class="bi bi-cart-plus-fill me-2"></i>
                    Create New Buyer Account
                </h5>
            </div>
            <div class="card-body p-4">
                <div class="alert alert-info">
                    <i class="bi bi-info-circle me-2"></i>
                    <strong>Admin Creation:</strong> This buyer account will be created as APPROVED. For companies like Kakira Sugar Works, set type as "First Tier Buyer".
                </div>

                <form id="createBuyerForm" class="needs-validation" novalidate>
                    <!-- Buyer Type -->
                    <h6 class="mb-3 fw-bold text-success">
                        <i class="bi bi-building me-2"></i>Buyer Type
                    </h6>

                    <div class="mb-4">
                        <label class="form-label">Buyer Category *</label>
                        <select class="form-select" name="buyer_type" id="buyer_type" required>
                            <option value="">Select Buyer Type...</option>
                            <option value="individual">Individual Buyer</option>
                            <option value="retailer">Retailer</option>
                            <option value="wholesaler">Wholesaler</option>
                            <option value="processor">Processor</option>
                            <option value="first_tier">First Tier Buyer (e.g., Kakira Sugar, Kinyara Sugar)</option>
                            <option value="exporter">Exporter</option>
                        </select>
                        <div class="form-text">First Tier = Large companies that buy directly from farmers</div>
                    </div>

                    <!-- Basic Information -->
                    <h6 class="mb-3 fw-bold text-success">
                        <i class="bi bi-person me-2"></i>Basic Information
                    </h6>

                    <div class="row g-3 mb-4">
                        <div class="col-md-6">
                            <label class="form-label" id="nameLabel">Name/Company Name *</label>
                            <input type="text" class="form-control" name="full_name" id="full_name" required minlength="3">
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">Phone Number *</label>
                            <input type="tel" class="form-control" name="phone_number" 
                                   placeholder="0700123456" required pattern="[0-9+]{10,13}">
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">Email *</label>
                            <input type="email" class="form-control" name="email" required>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">Password *</label>
                            <div class="input-group">
                                <input type="password" class="form-control" name="password" 
                                       id="password" required minlength="6">
                                <button class="btn btn-outline-secondary" type="button" 
                                        onclick="generatePassword()">
                                    <i class="bi bi-arrow-clockwise"></i>
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Business Information (shown for company types) -->
                    <div id="businessInfoSection" style="display:none;">
                        <h6 class="mb-3 fw-bold text-success">
                            <i class="bi bi-briefcase me-2"></i>Business Information
                        </h6>

                        <div class="row g-3 mb-4">
                            <div class="col-md-6">
                                <label class="form-label">Business Name *</label>
                                <input type="text" class="form-control" name="business_name" id="business_name">
                            </div>

                            <div class="col-md-6">
                                <label class="form-label">Business Registration Number</label>
                                <input type="text" class="form-control" name="business_registration">
                            </div>

                            <div class="col-md-6">
                                <label class="form-label">Tax ID / TIN</label>
                                <input type="text" class="form-control" name="tax_id">
                            </div>

                            <div class="col-md-6">
                                <label class="form-label">Business Phone</label>
                                <input type="tel" class="form-control" name="business_phone">
                            </div>

                            <div class="col-md-12">
                                <label class="form-label">Business Address</label>
                                <textarea class="form-control" name="business_address" rows="2"></textarea>
                            </div>
                        </div>
                    </div>

                    <!-- Location -->
                    <h6 class="mb-3 fw-bold text-success">
                        <i class="bi bi-geo-alt me-2"></i>Location
                    </h6>

                    <div class="row g-3 mb-4">
                        <div class="col-md-6">
                            <label class="form-label">Region *</label>
                            <select class="form-select" name="region_id" id="region_id" required>
                                <option value="">Select Region...</option>
                            </select>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">District *</label>
                            <select class="form-select" name="district_id" id="district_id" required disabled>
                                <option value="">Select District...</option>
                            </select>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">Subcounty</label>
                            <select class="form-select" name="subcounty_id" id="subcounty_id" disabled>
                                <option value="">Select Subcounty...</option>
                            </select>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">Parish</label>
                            <select class="form-select" name="parish_id" id="parish_id" disabled>
                                <option value="">Select Parish...</option>
                            </select>
                        </div>
                    </div>

                    <!-- Submit -->
                    <div class="d-flex gap-2 justify-content-end">
                        <a href="<?php echo APP_URL; ?>/admin/users.php?type=buyer" class="btn btn-secondary">
                            <i class="bi bi-x-circle me-2"></i>Cancel
                        </a>
                        <button type="submit" class="btn btn-success">
                            <i class="bi bi-check-circle me-2"></i>Create Buyer Account
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
jQuery(document).ready(function($) {

// Load regions
loadRegions();

function loadRegions() {
    $.get(APP_URL + '/api/locations.php?action=get_regions', function(response) {
        if (response.success) {
            const $select = $('#region_id');
            $select.empty().append('<option value="">Select Region...</option>');
            response.data.forEach(region => {
                $select.append(`<option value="${region.id}">${region.region_name}</option>`);
            });
        }
    });
}

// Buyer type change
$('#buyer_type').change(function() {
    const type = $(this).val();
    const isCompany = ['retailer', 'wholesaler', 'processor', 'first_tier', 'exporter'].includes(type);
    
    $('#businessInfoSection').toggle(isCompany);
    
    if (isCompany) {
        $('#nameLabel').text('Contact Person Name *');
        $('#business_name').attr('required', 'required');
        $('#full_name').attr('placeholder', 'Primary contact person');
    } else {
        $('#nameLabel').text('Full Name *');
        $('#business_name').removeAttr('required');
        $('#full_name').attr('placeholder', 'Individual buyer name');
    }
});

// Location cascade (same as extension worker)
$('#region_id').change(function() {
    const regionId = $(this).val();
    $('#district_id').prop('disabled', !regionId).html('<option value="">Select District...</option>');
    
    if (regionId) {
        $.get(APP_URL + '/api/locations.php', {action: 'get_districts', region_id: regionId}, function(response) {
            if (response.success) {
                response.data.forEach(d => {
                    $('#district_id').append(`<option value="${d.id}">${d.district_name}</option>`);
                });
            }
        });
    }
});

$('#district_id').change(function() {
    const districtId = $(this).val();
    $('#subcounty_id').prop('disabled', !districtId).html('<option value="">Select Subcounty...</option>');
    
    if (districtId) {
        $.get(APP_URL + '/api/locations.php', {action: 'get_subcounties', district_id: districtId}, function(response) {
            if (response.success) {
                response.data.forEach(s => {
                    $('#subcounty_id').append(`<option value="${s.id}">${s.subcounty_name}</option>`);
                });
            }
        });
    }
});

$('#subcounty_id').change(function() {
    const subcountyId = $(this).val();
    $('#parish_id').prop('disabled', !subcountyId).html('<option value="">Select Parish...</option>');
    
    if (subcountyId) {
        $.get(APP_URL + '/api/locations.php', {action: 'get_parishes', subcounty_id: subcountyId}, function(response) {
            if (response.success) {
                response.data.forEach(p => {
                    $('#parish_id').append(`<option value="${p.id}">${p.parish_name}</option>`);
                });
            }
        });
    }
});

// Form submission
$('#createBuyerForm').submit(function(e) {
    e.preventDefault();
    
    if (!this.checkValidity()) {
        e.stopPropagation();
        this.classList.add('was-validated');
        return;
    }
    
    const formData = $(this).serialize();
    
    showLoading();
    $.post(APP_URL + '/api/admin-user-management.php', formData + '&action=create_buyer', function(response) {
        hideLoading();
        if (response.success) {
            Swal.fire({
                icon: 'success',
                title: 'Buyer Account Created!',
                html: `
                    <p>${response.message}</p>
                    <div class="alert alert-info mt-3">
                        <strong>Login Credentials:</strong><br>
                        Phone: ${response.phone}<br>
                        Password: ${response.password || '(as set)'}
                    </div>
                `,
                confirmButtonText: 'View Buyers'
            }).then(() => {
                window.location.href = APP_URL + '/admin/users.php?type=buyer';
            });
        } else {
            showToast(response.message, 'error');
        }
    }, 'json').fail(function() {
        hideLoading();
        showToast('Connection error. Please try again.', 'error');
    });
});

}); // End document ready

function generatePassword() {
    const length = 8;
    const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    let password = "";
    for (let i = 0; i < length; i++) {
        password += charset.charAt(Math.floor(Math.random() * charset.length));
    }
    document.getElementById('password').value = password;
    showToast('Password generated: ' + password, 'success');
}
</script>

<?php renderAdminFooter(); ?>