<?php
require_once __DIR__ . '/../config/cors.php';
session_start();
require_once '../config/db.php';

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

// Handle both standard POST and JSON input
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Check if it's a JSON request
    $json = file_get_contents('php://input');
    $decoded = json_decode($json, true);

    if ($decoded) {
        $identity = trim($decoded['identity'] ?? '');
        $password = trim($decoded['password'] ?? '');
        $loginSource = trim($decoded['login_source'] ?? '');
    } else {
        $identity = trim($_POST['identity'] ?? '');
        $password = trim($_POST['password'] ?? '');
        $loginSource = trim($_POST['login_source'] ?? '');
    }
} else {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method Not Allowed']);
    exit;
}

if ($identity === '' || $password === '') {
    echo json_encode([
        'success' => false,
        'code' => 'missing_fields',
        'message' => 'Both NROI ID and Password are required.'
    ]);
    exit;
}

try {
    // 1. Check Admin Table (Admins log in with Username)
    $stmtAdmin = $pdo->prepare("SELECT * FROM admins WHERE username = ?");
    $stmtAdmin->execute([$identity]);
    $admin = $stmtAdmin->fetch();

    if ($admin) {
        if (password_verify($password, $admin['password'])) {
            $_SESSION['admin_id'] = $admin['id'];
            $_SESSION['admin_user'] = $admin['username'];
            $_SESSION['user_role'] = 'admin';

            echo json_encode([
                'success' => true,
                'role' => 'admin',
                'message' => 'Access granted!',
                'user_id' => $admin['id'],
                'name' => $admin['username'] ?? 'Admin',
                'email' => $admin['email'] ?? '',
            ]);
            exit;
        } else {
            echo json_encode([
                'success' => false,
                'code' => 'invalid_password',
                'message' => 'The password you entered is incorrect. Please try again.'
            ]);
            exit;
        }
    }

    // 2. Check Users Table (Users log in with NROI ID or Username)
    $stmtUser = $pdo->prepare("
        SELECT u.*,
               COALESCE(
                  (SELECT a1.area_name FROM areas a1 WHERE a1.area_name = u.area LIMIT 1),
                  (SELECT a2.area_name FROM areas a2 WHERE a2.id = u.area LIMIT 1),
                  u.area
               ) AS area_display
        FROM users u
        WHERE u.nroi_id = ? OR u.username = ?
    ");
    $stmtUser->execute([$identity, $identity]);
    $user = $stmtUser->fetch();

    if ($user) {
        if (password_verify($password, $user['password'])) {
            // Web Access Whitelist: Only AC, AAC, NROI, and PPSA are allowed to log in via web.
            $allowedWebRoles = ['AC', 'AAC', 'NROI', 'PPSA'];
            if ($loginSource === 'web' && !in_array($user['role'], $allowedWebRoles)) {
                echo json_encode([
                    'success' => false,
                    'code' => 'unauthorized',
                    'message' => 'Unauthorized Access'
                ]);
                exit;
            }

            // App Access Restriction: PPSA/NROI users cannot access the app.
            if ($loginSource !== 'web' && in_array($user['role'], ['NROI', 'PPSA'])) {
                echo json_encode([
                    'success' => false,
                    'code' => 'unauthorized',
                    'message' => 'Your account is restricted to web access only.'
                ]);
                exit;
            }

            // Email Confirmation Check
            if (isset($user['is_email_confirmed']) && $user['is_email_confirmed'] == 0) {
                echo json_encode([
                    'success' => false,
                    'code' => 'email_not_confirmed',
                    'message' => 'Please confirm your email address before logging in. Check your inbox for the confirmation link.'
                ]);
                exit;
            }

            // Status Checks
            if ($user['status'] === 'pending') {
                echo json_encode([
                    'success' => false,
                    'code' => 'pending',
                    'message' => 'your account is still in review and pending for approval'
                ]);
                exit;
            }

            if ($user['status'] === 'rejected') {
                echo json_encode([
                    'success' => false,
                    'code' => 'rejected',
                    'message' => 'Your account has been rejected. Please contact support for assistance.'
                ]);
                exit;
            }

            if ($user['status'] === 'deactivated') {
                echo json_encode([
                    'success' => false,
                    'code' => 'deactivated',
                    'message' => 'This account has been deactivated. Please contact support for assistance.'
                ]);
                exit;
            }

            // Set Session
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['nroi_id'] = $user['nroi_id'];
            $_SESSION['name'] = $user['first_name'];
            $_SESSION['user_role'] = $user['role'];
            $_SESSION['area'] = $user['area'] ?? '';
            $_SESSION['is_first_login'] = $user['is_first_login'] ?? 0;

            echo json_encode([
                'success' => true,
                'role' => $user['role'],
                'message' => 'Access granted!',
                'name' => trim($user['first_name'] . ' ' . $user['last_name']),
                'first_name' => $user['first_name'],
                'last_name' => $user['last_name'],
                'middle_name' => $user['middle_name'],
                'email' => $user['email'],
                'phone_number' => $user['phone_number'],
                'user_id' => $user['id'],
                'nroi_id' => $user['nroi_id'],
                'ppsa_id' => $user['ppsa_id'],
                'area' => $user['area_display'] ?? $user['area'] ?? '',
                'rank' => $user['rank'] ?? '',
                'status' => $user['status'] ?? 'approved',
                'profile_photo' => !empty($user['profile_photo']) ? $user['profile_photo'] : '',
                'gender' => $user['gender'],
                'dob' => $user['dob'],
                'age' => $user['age'],
                'region' => $user['region'],
                'province' => $user['province'],
                'city_municipality' => $user['city_municipality'],
                'barangay' => $user['barangay'],
                'zipcode' => $user['zipcode'],
                'street' => $user['street'],
                'facebook_link' => $user['facebook_link'],
                'viber_number' => $user['viber_number'],
                'telegram_number' => $user['telegram_number'],
                'emergency_contact_name' => $user['emergency_contact_name'],
                'emergency_contact_number' => $user['emergency_contact_number'],
                'is_first_login' => $user['is_first_login'] ?? 0
            ]);
            exit;
        } else {
            echo json_encode([
                'success' => false,
                'code' => 'invalid_password',
                'message' => 'The password you entered is incorrect. Please try again.'
            ]);
            exit;
        }
    }

    // 3. Not Found (Combined message for security)
    echo json_encode([
        'success' => false,
        'code' => 'not_found',
        'message' => 'No account was found matching that NROI ID or Username.'
    ]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'A database error occurred. Please try again later.']);
}