<?php
/**
 * AIMS - Authentication API
 * Handles login, registration, OTP verification
 * File: api/auth.php
 */

// Define access constant
define('AIMS_ACCESS', true);

// Include configuration
require_once __DIR__ . '/../config/config.php';

// Include User class
require_once __DIR__ . '/../classes/User.php';

// Set JSON header
header('Content-Type: application/json');

// Enable error reporting for debugging (remove in production)
if (APP_DEBUG) {
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
}

try {
    // Get database connection
    $database = new Database();
    $db = $database->getConnection();
    
    // Create User instance
    $user = new User($db);
    
    // Get action from POST
    $action = $_POST['action'] ?? '';
    
    switch ($action) {
        case 'login':
            handleLogin($user);
            break;
            
        case 'register':
            handleRegister($user);
            break;
            
        case 'verify_otp':
            handleVerifyOTP($user);
            break;
            
        case 'resend_otp':
            handleResendOTP($user);
            break;
            
        case 'logout':
            handleLogout();
            break;
            
        default:
            jsonError('Invalid action', 400);
    }
} catch (Exception $e) {
    logError('Auth API Error: ' . $e->getMessage());
    jsonError('An error occurred: ' . $e->getMessage(), 500);
}

/**
 * Handle user login
 */
function handleLogin($user) {
    try {
        // Validate input
        if (empty($_POST['phone']) || empty($_POST['password'])) {
            jsonError('Phone number and password are required');
        }
        
        $phone = sanitize($_POST['phone']);
        $password = $_POST['password'];
        
        // Attempt login
        $result = $user->login($phone, $password);
        
        if ($result['success']) {
            // Determine redirect based on user type
            $redirectUrl = APP_URL . '/dashboard/';
            
            if (isset($result['user']) && $result['user']['user_type'] === 'admin') {
                $redirectUrl = APP_URL . '/admin/';
            }
            
            echo json_encode([
                'success' => true,
                'message' => $result['message'],
                'redirect' => $redirectUrl,
                'user_type' => $result['user']['user_type'] ?? 'farmer'
            ]);
            exit;
        } else {
            // Check if verification is required
            if (isset($result['requires_verification'])) {
                echo json_encode([
                    'success' => false,
                    'message' => $result['message'],
                    'requires_verification' => true,
                    'phone' => $result['phone']
                ]);
                exit;
            }
            
            // Check if pending approval
            if (isset($result['pending_approval'])) {
                echo json_encode([
                    'success' => false,
                    'message' => $result['message'],
                    'pending_approval' => true
                ]);
                exit;
            }
            
            // Check if rejected
            if (isset($result['rejected'])) {
                echo json_encode([
                    'success' => false,
                    'message' => $result['message'],
                    'rejected' => true
                ]);
                exit;
            }
            
            jsonError($result['message']);
        }
    } catch (Exception $e) {
        logError('Login Handler Error: ' . $e->getMessage());
        jsonError('Login error: ' . $e->getMessage());
    }
}

/**
 * Handle user registration
 */
function handleRegister($user) {
    try {
        // Validate required fields
        $required = ['full_name', 'phone_number', 'password', 'user_type'];
        foreach ($required as $field) {
            if (empty($_POST[$field])) {
                jsonError(ucfirst(str_replace('_', ' ', $field)) . ' is required');
            }
        }
        
        // Validate phone format
        $phone = validatePhone($_POST['phone_number']);
        if (!$phone) {
            jsonError('Invalid phone number format. Use 0700000000 or +256700000000');
        }
        
        // Validate password length
        if (strlen($_POST['password']) < 6) {
            jsonError('Password must be at least 6 characters');
        }
        
        // Prepare registration data
        $data = [
            'full_name' => sanitize($_POST['full_name']),
            'phone_number' => $phone,
            'password' => $_POST['password'],
            'email' => sanitize($_POST['email'] ?? ''),
            'user_type' => sanitize($_POST['user_type']),
            'language' => $_POST['language'] ?? 'en',
            
            // Location IDs (hierarchical)
            'region_id' => !empty($_POST['region_id']) ? (int)$_POST['region_id'] : null,
            'district_id' => !empty($_POST['district_id']) ? (int)$_POST['district_id'] : null,
            'subcounty_id' => !empty($_POST['subcounty_id']) ? (int)$_POST['subcounty_id'] : null,
            'parish_id' => !empty($_POST['parish_id']) ? (int)$_POST['parish_id'] : null,
            'village_id' => !empty($_POST['village_id']) ? (int)$_POST['village_id'] : null,
        ];
        
        // Add buyer-specific fields
        if ($data['user_type'] === 'buyer') {
            $data['buyer_type'] = sanitize($_POST['buyer_type'] ?? 'individual');
            $data['business_name'] = sanitize($_POST['business_name'] ?? '');
            $data['business_registration'] = sanitize($_POST['business_registration'] ?? '');
            $data['tax_id'] = sanitize($_POST['tax_id'] ?? '');
        }
        
        // Add extension officer fields
        if ($data['user_type'] === 'extension_officer') {
            $data['organization'] = sanitize($_POST['organization'] ?? '');
            $data['qualification'] = sanitize($_POST['qualification'] ?? '');
            $data['experience'] = !empty($_POST['experience']) ? (int)$_POST['experience'] : 0;
            $data['specialization'] = sanitize($_POST['specialization'] ?? '');
        }
        
        // Attempt registration
        $result = $user->register($data);
        
        if ($result['success']) {
            // Return success with OTP (remove in production)
            echo json_encode([
                'success' => true,
                'message' => $result['message'],
                'otp' => $result['otp'] ?? null, // Remove in production
                'user_id' => $result['user_id'],
                'requires_approval' => $result['requires_approval'] ?? false
            ]);
            exit;
        } else {
            jsonError($result['message']);
        }
    } catch (Exception $e) {
        logError('Registration Handler Error: ' . $e->getMessage());
        jsonError('Registration error: ' . $e->getMessage());
    }
}

/**
 * Handle OTP verification
 */
function handleVerifyOTP($user) {
    try {
        // Validate input
        if (empty($_POST['phone']) || empty($_POST['otp'])) {
            jsonError('Phone number and OTP are required');
        }
        
        $phone = validatePhone($_POST['phone']);
        $otp = sanitize($_POST['otp']);
        
        if (!$phone) {
            jsonError('Invalid phone number');
        }
        
        // Verify OTP
        $result = $user->verifyOTP($phone, $otp);
        
        if ($result['success']) {
            // Check if pending approval
            if (isset($result['pending_approval']) && $result['pending_approval']) {
                echo json_encode([
                    'success' => true,
                    'message' => $result['message'],
                    'pending_approval' => true,
                    'redirect' => APP_URL . '/auth/login.php'
                ]);
                exit;
            }
            
            // Determine redirect based on user type
            $redirectUrl = APP_URL . '/dashboard/';
            if (isset($_SESSION['user_type']) && $_SESSION['user_type'] === 'admin') {
                $redirectUrl = APP_URL . '/admin/';
            }
            
            echo json_encode([
                'success' => true,
                'message' => $result['message'],
                'redirect' => $redirectUrl
            ]);
            exit;
        } else {
            jsonError($result['message']);
        }
    } catch (Exception $e) {
        logError('OTP Verification Error: ' . $e->getMessage());
        jsonError('Verification error: ' . $e->getMessage());
    }
}

/**
 * Handle resend OTP
 */
function handleResendOTP($user) {
    try {
        // Validate input
        if (empty($_POST['phone'])) {
            jsonError('Phone number is required');
        }
        
        $phone = validatePhone($_POST['phone']);
        
        if (!$phone) {
            jsonError('Invalid phone number');
        }
        
        // Resend OTP
        $result = $user->resendOTP($phone);
        
        if ($result['success']) {
            echo json_encode([
                'success' => true,
                'message' => $result['message'],
                'otp' => $result['otp'] ?? null // Remove in production
            ]);
            exit;
        } else {
            jsonError($result['message']);
        }
    } catch (Exception $e) {
        logError('Resend OTP Error: ' . $e->getMessage());
        jsonError('Resend error: ' . $e->getMessage());
    }
}

/**
 * Handle logout
 */
function handleLogout() {
    try {
        destroySession();
        echo json_encode([
            'success' => true,
            'message' => 'Logged out successfully',
            'redirect' => APP_URL . '/auth/login.php'
        ]);
        exit;
    } catch (Exception $e) {
        logError('Logout Error: ' . $e->getMessage());
        jsonError('Logout error: ' . $e->getMessage());
    }
}
?>