<?php
/**
 * ============================================================================
 * auth/register.php - Enhanced Registration with Location Hierarchy
 * ============================================================================
 */

define('AIMS_ACCESS', true);
require_once '../config/config.php';

if (isLoggedIn()) {
    header('Location: ../dashboard/');
    exit();
}

$pageTitle = 'Register - AIMS';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?></title>
    
    <!-- Bootstrap 5.3 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" rel="stylesheet">
    
    <!-- Toastify CSS -->
    <link href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css" rel="stylesheet">
    
    <style>
        :root {
            --primary-color: #059669;
            --primary-dark: #047857;
            --primary-light: #10b981;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        
        .auth-card {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            max-width: 600px;
            width: 100%;
            overflow: hidden;
            animation: fadeInUp 0.6s ease;
        }
        
        .auth-header {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-light) 100%);
            padding: 30px;
            text-align: center;
            color: white;
        }
        
        .auth-logo {
            font-size: 3rem;
            margin-bottom: 10px;
        }
        
        .auth-body {
            padding: 30px;
            max-height: 70vh;
            overflow-y: auto;
        }
        
        .user-type-selector {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 10px;
            margin-bottom: 20px;
        }
        
        .user-type-card {
            border: 2px solid #e5e7eb;
            border-radius: 10px;
            padding: 15px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .user-type-card:hover {
            border-color: var(--primary-color);
            background-color: #f0fdf4;
        }
        
        .user-type-card.active {
            border-color: var(--primary-color);
            background-color: #dcfce7;
        }
        
        .user-type-card input[type="radio"] {
            display: none;
        }
        
        .user-type-icon {
            font-size: 2rem;
            margin-bottom: 5px;
        }
        
        .password-toggle {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            color: #6b7280;
            z-index: 10;
        }
        
        .additional-fields {
            display: none;
            animation: fadeIn 0.3s ease;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
            border: none;
            padding: 12px;
            font-weight: 600;
            border-radius: 10px;
            transition: all 0.3s ease;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(5, 150, 105, 0.3);
        }
        
        @keyframes fadeInUp {
            from { opacity: 0; transform: translateY(30px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        @media (max-width: 576px) {
            .auth-body {
                padding: 20px;
            }
            
            .user-type-selector {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="auth-card">
        <div class="auth-header">
            <div class="auth-logo">🌾</div>
            <h1 class="h3 fw-bold mb-1">Join AIMS</h1>
            <p class="mb-0 small">Start your agricultural journey today</p>
        </div>
        
        <div class="auth-body">
            <form id="registerForm" novalidate>
                <!-- User Type Selection -->
                <div class="mb-4">
                    <label class="form-label fw-bold">I am a:</label>
                    <div class="user-type-selector">
                        <div class="user-type-card active" data-type="farmer">
                            <input type="radio" name="user_type" value="farmer" checked>
                            <div class="user-type-icon">👨‍🌾</div>
                            <div class="small fw-semibold">Farmer</div>
                        </div>
                        <div class="user-type-card" data-type="buyer">
                            <input type="radio" name="user_type" value="buyer">
                            <div class="user-type-icon">🛒</div>
                            <div class="small fw-semibold">Buyer</div>
                        </div>
                        <div class="user-type-card" data-type="extension_officer">
                            <input type="radio" name="user_type" value="extension_officer">
                            <div class="user-type-icon">👨‍🏫</div>
                            <div class="small fw-semibold">Extension Officer</div>
                        </div>
                    </div>
                </div>

                <!-- Basic Information -->
                <div class="mb-3">
                    <div class="form-floating">
                        <input type="text" class="form-control" id="fullName" placeholder="Full Name" required>
                        <label for="fullName"><i class="bi bi-person me-2"></i>Full Name</label>
                        <div class="invalid-feedback">Please enter your full name</div>
                    </div>
                </div>
                
                <div class="mb-3">
                    <div class="form-floating">
                        <input type="tel" class="form-control" id="phone" placeholder="Phone Number" required>
                        <label for="phone"><i class="bi bi-phone me-2"></i>Phone Number</label>
                        <div class="invalid-feedback">Please enter a valid phone number</div>
                    </div>
                    <small class="text-muted">Format: 0700000000 or +256700000000</small>
                </div>

                <div class="mb-3">
                    <div class="form-floating">
                        <input type="email" class="form-control" id="email" placeholder="Email (Optional)">
                        <label for="email"><i class="bi bi-envelope me-2"></i>Email (Optional)</label>
                    </div>
                </div>
                
                <!-- Location Selection -->
                <div class="row g-3 mb-3">
                    <div class="col-md-6">
                        <div class="form-floating">
                            <select class="form-select" id="region" required>
                                <option value="">Choose Region...</option>
                            </select>
                            <label for="region"><i class="bi bi-map me-2"></i>Region</label>
                            <div class="invalid-feedback">Please select region</div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-floating">
                            <select class="form-select" id="district" required disabled>
                                <option value="">Choose District...</option>
                            </select>
                            <label for="district"><i class="bi bi-geo-alt me-2"></i>District</label>
                            <div class="invalid-feedback">Please select district</div>
                        </div>
                    </div>
                </div>

                <div class="row g-3 mb-3">
                    <div class="col-md-6">
                        <div class="form-floating">
                            <select class="form-select" id="subcounty" required disabled>
                                <option value="">Choose Subcounty...</option>
                            </select>
                            <label for="subcounty"><i class="bi bi-signpost me-2"></i>Subcounty</label>
                            <div class="invalid-feedback">Please select subcounty</div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-floating">
                            <select class="form-select" id="parish" disabled>
                                <option value="">Choose Parish...</option>
                            </select>
                            <label for="parish"><i class="bi bi-signpost-2 me-2"></i>Parish (Optional)</label>
                        </div>
                    </div>
                </div>

                <div class="mb-3">
                    <div class="form-floating">
                        <select class="form-select" id="village" disabled>
                            <option value="">Choose Village...</option>
                        </select>
                        <label for="village"><i class="bi bi-house me-2"></i>Village (Optional)</label>
                    </div>
                </div>

                <!-- Buyer Additional Fields -->
                <div id="buyerFields" class="additional-fields">
                    <hr class="my-4">
                    <h6 class="mb-3 fw-bold">Business Information</h6>
                    
                    <div class="mb-3">
                        <div class="form-floating">
                            <select class="form-select" id="buyerType">
                                <option value="">Choose 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="exporter">Exporter</option>
                            </select>
                            <label for="buyerType"><i class="bi bi-briefcase me-2"></i>Buyer Type</label>
                        </div>
                    </div>

                    <div class="mb-3">
                        <div class="form-floating">
                            <input type="text" class="form-control" id="businessName" placeholder="Business Name">
                            <label for="businessName"><i class="bi bi-building me-2"></i>Business Name</label>
                        </div>
                    </div>

                    <div class="mb-3">
                        <div class="form-floating">
                            <input type="text" class="form-control" id="businessRegistration" placeholder="Registration Number">
                            <label for="businessRegistration"><i class="bi bi-card-text me-2"></i>Registration Number (Optional)</label>
                        </div>
                    </div>

                    <div class="mb-3">
                        <div class="form-floating">
                            <input type="text" class="form-control" id="taxId" placeholder="Tax ID">
                            <label for="taxId"><i class="bi bi-receipt me-2"></i>Tax ID (Optional)</label>
                        </div>
                    </div>
                </div>

                <!-- Extension Officer Additional Fields -->
                <div id="extensionFields" class="additional-fields">
                    <hr class="my-4">
                    <h6 class="mb-3 fw-bold">Professional Information</h6>
                    
                    <div class="mb-3">
                        <div class="form-floating">
                            <input type="text" class="form-control" id="organization" placeholder="Organization">
                            <label for="organization"><i class="bi bi-building me-2"></i>Organization</label>
                        </div>
                        <small class="text-muted">e.g., NAADS, MAAIF, NGO name</small>
                    </div>

                    <div class="row g-3 mb-3">
                        <div class="col-md-6">
                            <div class="form-floating">
                                <select class="form-select" id="qualification">
                                    <option value="">Choose...</option>
                                    <option value="certificate">Certificate</option>
                                    <option value="diploma">Diploma</option>
                                    <option value="degree">Degree</option>
                                    <option value="masters">Masters</option>
                                    <option value="phd">PhD</option>
                                </select>
                                <label for="qualification"><i class="bi bi-award me-2"></i>Qualification</label>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-floating">
                                <input type="number" class="form-control" id="experience" placeholder="Years" min="0">
                                <label for="experience"><i class="bi bi-calendar me-2"></i>Years of Experience</label>
                            </div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <div class="form-floating">
                            <input type="text" class="form-control" id="specialization" placeholder="Specialization">
                            <label for="specialization"><i class="bi bi-mortarboard me-2"></i>Specialization</label>
                        </div>
                        <small class="text-muted">e.g., Agronomy, Animal Husbandry, Crop Science</small>
                    </div>
                </div>
                
                <!-- Password Fields -->
                <div class="mb-3">
                    <div class="form-floating position-relative">
                        <input type="password" class="form-control" id="password" placeholder="Password" required minlength="6">
                        <label for="password"><i class="bi bi-lock me-2"></i>Password</label>
                        <i class="bi bi-eye password-toggle" id="togglePassword"></i>
                        <div class="invalid-feedback">Password must be at least 6 characters</div>
                    </div>
                </div>
                
                <div class="mb-3">
                    <div class="form-floating position-relative">
                        <input type="password" class="form-control" id="confirmPassword" placeholder="Confirm Password" required>
                        <label for="confirmPassword"><i class="bi bi-lock-fill me-2"></i>Confirm Password</label>
                        <i class="bi bi-eye password-toggle" id="toggleConfirm"></i>
                        <div class="invalid-feedback">Passwords do not match</div>
                    </div>
                </div>
                
                <div class="mb-3">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="agreeTerms" required>
                        <label class="form-check-label" for="agreeTerms">
                            I agree to the <a href="#" class="text-decoration-none">Terms & Conditions</a>
                        </label>
                        <div class="invalid-feedback">You must agree to continue</div>
                    </div>
                </div>
                
                <div class="alert alert-info small" id="approvalNotice" style="display: none;">
                    <i class="bi bi-info-circle me-2"></i>
                    <strong>Note:</strong> Your account will require admin approval before you can access all features.
                </div>

                <button type="submit" class="btn btn-primary w-100 mb-3">
                    <i class="bi bi-person-plus me-2"></i>Create Account
                </button>
            </form>
            
            <hr>
            
            <p class="text-center mb-0 small">
                Already have an account? <a href="login.php" class="text-decoration-none fw-bold">Login Here</a>
            </p>
        </div>
    </div>

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    
    <!-- Bootstrap -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <!-- Toastify -->
    <script src="https://cdn.jsdelivr.net/npm/toastify-js"></script>
    
    <script>
        const APP_URL = '<?php echo APP_URL; ?>';
        
        function showToast(message, type = 'info') {
            const colors = {
                success: 'linear-gradient(135deg, #22c55e 0%, #16a34a 100%)',
                error: 'linear-gradient(135deg, #ef4444 0%, #dc2626 100%)',
                warning: 'linear-gradient(135deg, #f59e0b 0%, #d97706 100%)',
                info: 'linear-gradient(135deg, #3b82f6 0%, #2563eb 100%)'
            };
            
            Toastify({
                text: message,
                duration: 3000,
                gravity: "top",
                position: "right",
                style: { 
                    background: colors[type], 
                    borderRadius: "10px", 
                    padding: "15px 20px" 
                },
                stopOnFocus: true
            }).showToast();
        }

        // User type selection
        $('.user-type-card').click(function() {
            $('.user-type-card').removeClass('active');
            $(this).addClass('active');
            $(this).find('input[type="radio"]').prop('checked', true);
            
            const userType = $(this).data('type');
            
            // Hide all additional fields
            $('.additional-fields').hide();
            
            // Show relevant fields
            if (userType === 'buyer') {
                $('#buyerFields').show();
                $('#approvalNotice').show();
            } else if (userType === 'extension_officer') {
                $('#extensionFields').show();
                $('#approvalNotice').show();
            } else {
                $('#approvalNotice').hide();
            }
        });
        
        // Password toggle
        $('#togglePassword').click(function() {
            const input = $('#password');
            const type = input.attr('type') === 'password' ? 'text' : 'password';
            input.attr('type', type);
            $(this).toggleClass('bi-eye bi-eye-slash');
        });
        
        $('#toggleConfirm').click(function() {
            const input = $('#confirmPassword');
            const type = input.attr('type') === 'password' ? 'text' : 'password';
            input.attr('type', type);
            $(this).toggleClass('bi-eye bi-eye-slash');
        });

        // Load regions on page load
        $(document).ready(function() {
            loadRegions();
        });

        function loadRegions() {
            $.ajax({
                url: APP_URL + '/api/locations.php',
                method: 'GET',
                data: { action: 'get_regions' },
                success: function(response) {
                    if (response.success) {
                        const select = $('#region');
                        select.empty().append('<option value="">Choose Region...</option>');
                        response.data.forEach(region => {
                            select.append(`<option value="${region.id}">${region.region_name}</option>`);
                        });
                    } else {
                        showToast('Failed to load regions', 'error');
                    }
                },
                error: function(xhr) {
                    console.error('Load regions error:', xhr);
                    showToast('Failed to load regions', 'error');
                }
            });
        }

        // Load districts when region changes
        $('#region').change(function() {
            const regionId = $(this).val();
            $('#district').prop('disabled', !regionId).empty().append('<option value="">Choose District...</option>');
            $('#subcounty, #parish, #village').prop('disabled', true).empty().append('<option value="">Choose...</option>');
            
            if (regionId) {
                $.ajax({
                    url: APP_URL + '/api/locations.php',
                    method: 'GET',
                    data: { action: 'get_districts', region_id: regionId },
                    success: function(response) {
                        if (response.success) {
                            const select = $('#district');
                            response.data.forEach(district => {
                                select.append(`<option value="${district.id}">${district.district_name}</option>`);
                            });
                        }
                    },
                    error: function(xhr) {
                        console.error('Load districts error:', xhr);
                        showToast('Failed to load districts', 'error');
                    }
                });
            }
        });

        // Load subcounties when district changes
        $('#district').change(function() {
            const districtId = $(this).val();
            $('#subcounty').prop('disabled', !districtId).empty().append('<option value="">Choose Subcounty...</option>');
            $('#parish, #village').prop('disabled', true).empty().append('<option value="">Choose...</option>');
            
            if (districtId) {
                $.ajax({
                    url: APP_URL + '/api/locations.php',
                    method: 'GET',
                    data: { action: 'get_subcounties', district_id: districtId },
                    success: function(response) {
                        if (response.success) {
                            const select = $('#subcounty');
                            response.data.forEach(subcounty => {
                                select.append(`<option value="${subcounty.id}">${subcounty.subcounty_name}</option>`);
                            });
                        }
                    },
                    error: function(xhr) {
                        console.error('Load subcounties error:', xhr);
                        showToast('Failed to load subcounties', 'error');
                    }
                });
            }
        });

        // Load parishes when subcounty changes
        $('#subcounty').change(function() {
            const subcountyId = $(this).val();
            $('#parish').prop('disabled', !subcountyId).empty().append('<option value="">Choose Parish...</option>');
            $('#village').prop('disabled', true).empty().append('<option value="">Choose Village...</option>');
            
            if (subcountyId) {
                $.ajax({
                    url: APP_URL + '/api/locations.php',
                    method: 'GET',
                    data: { action: 'get_parishes', subcounty_id: subcountyId },
                    success: function(response) {
                        if (response.success) {
                            const select = $('#parish');
                            response.data.forEach(parish => {
                                select.append(`<option value="${parish.id}">${parish.parish_name}</option>`);
                            });
                        }
                    },
                    error: function(xhr) {
                        console.error('Load parishes error:', xhr);
                        showToast('Failed to load parishes', 'error');
                    }
                });
            }
        });

        // Load villages when parish changes
        $('#parish').change(function() {
            const parishId = $(this).val();
            $('#village').prop('disabled', !parishId).empty().append('<option value="">Choose Village...</option>');
            
            if (parishId) {
                $.ajax({
                    url: APP_URL + '/api/locations.php',
                    method: 'GET',
                    data: { action: 'get_villages', parish_id: parishId },
                    success: function(response) {
                        if (response.success) {
                            const select = $('#village');
                            response.data.forEach(village => {
                                select.append(`<option value="${village.id}">${village.village_name}</option>`);
                            });
                        }
                    },
                    error: function(xhr) {
                        console.error('Load villages error:', xhr);
                        showToast('Failed to load villages', 'error');
                    }
                });
            }
        });
        
        // Form submission
        $('#registerForm').submit(function(e) {
            e.preventDefault();
            
            const password = $('#password').val();
            const confirmPassword = $('#confirmPassword').val();
            
            // Check password match
            if (password !== confirmPassword) {
                $('#confirmPassword').addClass('is-invalid');
                showToast('Passwords do not match', 'error');
                return;
            }
            
            // Remove invalid class if passwords match
            $('#confirmPassword').removeClass('is-invalid');
            
            // Check form validity
            if (!this.checkValidity()) {
                e.stopPropagation();
                $(this).addClass('was-validated');
                showToast('Please fill in all required fields', 'warning');
                return;
            }
            
            const btn = $(this).find('button[type="submit"]');
            const originalHtml = btn.html();
            btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span>Creating account...');
            
            const userType = $('input[name="user_type"]:checked').val();
            const formData = {
                action: 'register',
                user_type: userType,
                full_name: $('#fullName').val(),
                phone_number: $('#phone').val(),
                email: $('#email').val() || '',
                password: password,
                region_id: $('#region').val(),
                district_id: $('#district').val(),
                subcounty_id: $('#subcounty').val(),
                parish_id: $('#parish').val() || '',
                village_id: $('#village').val() || ''
            };

            // Add buyer-specific fields
            if (userType === 'buyer') {
                formData.buyer_type = $('#buyerType').val();
                formData.business_name = $('#businessName').val();
                formData.business_registration = $('#businessRegistration').val();
                formData.tax_id = $('#taxId').val();
            }

            // Add extension officer fields
            if (userType === 'extension_officer') {
                formData.organization = $('#organization').val();
                formData.qualification = $('#qualification').val();
                formData.experience = $('#experience').val();
                formData.specialization = $('#specialization').val();
            }
            
            $.ajax({
                url: APP_URL + '/api/auth.php',
                method: 'POST',
                dataType: 'json',
                data: formData,
                success: function(response) {
                    if (response.success) {
                        let message = 'Registration successful!';
                        let htmlContent = `<p class="mb-3">${message}</p>`;
                        
                        if (userType !== 'farmer') {
                            htmlContent += '<p class="text-muted small mb-3">Your account will be reviewed by an administrator.</p>';
                        }
                        
                        if (response.otp) {
                            htmlContent += `<div class="alert alert-warning mb-0">
                                <strong>Development OTP:</strong> ${response.otp}
                            </div>`;
                        }
                        
                        Swal.fire({
                            title: 'Success!',
                            html: htmlContent,
                            icon: 'success',
                            confirmButtonColor: '#059669',
                            confirmButtonText: 'Verify Phone Number'
                        }).then(() => {
                            window.location.href = 'verify-otp.php?phone=' + encodeURIComponent($('#phone').val());
                        });
                    } else {
                        showToast(response.message || 'Registration failed', 'error');
                        btn.prop('disabled', false).html(originalHtml);
                    }
                },
                error: function(xhr) {
                    console.error('Registration error:', xhr);
                    let errorMsg = 'Connection error. Please try again.';
                    
                    if (xhr.responseJSON && xhr.responseJSON.message) {
                        errorMsg = xhr.responseJSON.message;
                    } else if (xhr.responseText) {
                        try {
                            const resp = JSON.parse(xhr.responseText);
                            errorMsg = resp.message || errorMsg;
                        } catch(e) {
                            console.error('Parse error:', e);
                        }
                    }
                    
                    showToast(errorMsg, 'error');
                    btn.prop('disabled', false).html(originalHtml);
                }
            });
        });
    </script>
</body>
</html>