<?php
/**
 * Authentication API
 * فوترة بلس - POS System
 * 
 * Handles: login, token generation, token verification
 */

require_once 'db.php';

// Only run switch statement when auth.php is accessed directly (not when included by other files)
if (basename($_SERVER['SCRIPT_FILENAME']) === 'auth.php') {
    // Get action from query string
    $action = $_GET['action'] ?? '';

    switch ($action) {
        case 'login':
            handleLogin();
            break;
        case 'verify':
            handleVerify();
            break;
        case 'seller-login':
            handleSellerLogin();
            break;
        case 'employee-login':
            handleEmployeeLogin();
            break;
        case 'refresh-token':
            handleRefreshToken();
            break;
        default:
            jsonResponse(false, 'Invalid action', null, 400);
    }
}

/**
 * Handle admin/user login
 */
function handleLogin() {
    global $pdo;
    
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        jsonResponse(false, 'Method not allowed', null, 405);
    }
    
    $input = getJsonInput();
    $username = sanitize($input['username'] ?? '');
    $password = $input['password'] ?? '';
    
    if (empty($username) || empty($password)) {
        jsonResponse(false, 'Username and password are required', null, 400);
    }
    
    try {
        // Check admins table first
        $stmt = $pdo->prepare("SELECT * FROM admins WHERE username = ? LIMIT 1");
        $stmt->execute([$username]);
        $user = $stmt->fetch();
        
        if ($user && $password === $user['password']) {
            $token = generateToken($user['id'], 'admin');
            jsonResponse(true, 'Login successful', [
                'token' => $token,
                'user' => [
                    'id' => $user['id'],
                    'username' => $user['username'],
                    'admin_name' => $user['admin_name'],
                    'role' => 'admin'
                ]
            ]);
        }
        
        // Check sellers table
        $stmt = $pdo->prepare("SELECT * FROM sellers WHERE username = ? LIMIT 1");
        $stmt->execute([$username]);
        $seller = $stmt->fetch();
        
        if ($seller && $password === $seller['password']) {
            $token = generateToken($seller['id'], 'seller');
            jsonResponse(true, 'Login successful', [
                'token' => $token,
                'user' => [
                    'id' => $seller['id'],
                    'username' => $seller['username'],
                    'seller_name' => $seller['seller_name'],
                    'role' => 'seller'
                ],
                'seller' => $seller
            ]);
        }
        
        jsonResponse(false, 'Invalid username or password', null, 401);
        
    } catch (PDOException $e) {
        jsonResponse(false, 'Login failed: ' . $e->getMessage(), null, 500);
    }
}

/**
 * Handle seller login specifically
 */
function handleSellerLogin() {
    global $pdo;
    
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        jsonResponse(false, 'Method not allowed', null, 405);
    }
    
    $input = getJsonInput();
    $username = sanitize($input['username'] ?? '');
    $password = $input['password'] ?? '';
    
    if (empty($username) || empty($password)) {
        jsonResponse(false, 'Username and password are required', null, 400);
    }
    
    try {
        $stmt = $pdo->prepare("SELECT * FROM sellers WHERE username = ? LIMIT 1");
        $stmt->execute([$username]);
        $seller = $stmt->fetch();
        
        if ($seller && $password === $seller['password']) {
            $token = generateToken($seller['id'], 'seller');
            jsonResponse(true, 'Login successful', [
                'token' => $token,
                'seller' => $seller
            ]);
        }
        
        jsonResponse(false, 'Invalid username or password', null, 401);
        
    } catch (PDOException $e) {
        jsonResponse(false, 'Login failed: ' . $e->getMessage(), null, 500);
    }
}

/**
 * Handle employee PIN login
 */
function handleEmployeeLogin() {
    global $pdo;
    
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        jsonResponse(false, 'Method not allowed', null, 405);
    }
    
    $input = getJsonInput();
    $pin = sanitize($input['pin'] ?? '');
    $sellerId = sanitize($input['seller_id'] ?? '');
    
    if (empty($pin) || empty($sellerId)) {
        jsonResponse(false, 'PIN and seller_id are required', null, 400);
    }
    
    try {
        $stmt = $pdo->prepare("SELECT * FROM employees WHERE pin_code = ? AND seller_id = ? AND is_active = 1 LIMIT 1");
        $stmt->execute([$pin, $sellerId]);
        $employee = $stmt->fetch();
        
        if ($employee) {
            $token = generateToken($employee['id'], 'employee');
            jsonResponse(true, 'Login successful', [
                'token' => $token,
                'employee' => $employee
            ]);
        }
        
        jsonResponse(false, 'Invalid PIN', null, 401);
        
    } catch (PDOException $e) {
        jsonResponse(false, 'Login failed: ' . $e->getMessage(), null, 500);
    }
}

/**
 * Verify token validity
 */
function handleVerify() {
    $token = getBearerToken() ?? ($_GET['token'] ?? '');
    
    if (empty($token)) {
        jsonResponse(false, 'Token is required', null, 400);
    }
    
    $decoded = verifyToken($token);
    
    if ($decoded) {
        jsonResponse(true, 'Token is valid', $decoded);
    } else {
        jsonResponse(false, 'Invalid or expired token', null, 401);
    }
}

/**
 * Generate JWT-style token
 */
function generateToken($userId, $role) {
    $header = base64_encode(json_encode(['alg' => 'HS256', 'typ' => 'JWT']));
    $payload = base64_encode(json_encode([
        'user_id' => $userId,
        'role' => $role,
        'iat' => time(),
        'exp' => time() + TOKEN_EXPIRY
    ]));
    $signature = hash_hmac('sha256', "$header.$payload", JWT_SECRET);
    
    return "$header.$payload.$signature";
}

/**
 * Verify JWT-style token
 */
function verifyToken($token) {
    $parts = explode('.', $token);
    
    if (count($parts) !== 3) {
        return false;
    }
    
    list($header, $payload, $signature) = $parts;
    
    $expectedSignature = hash_hmac('sha256', "$header.$payload", JWT_SECRET);
    
    if (!hash_equals($expectedSignature, $signature)) {
        return false;
    }
    
    $decoded = json_decode(base64_decode($payload), true);
    
    if (!$decoded || $decoded['exp'] < time()) {
        return false;
    }
    
    return $decoded;
}

/**
 * Get Bearer token from Authorization header
 */
function getBearerToken() {
    $headers = getallheaders();
    $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
    
    if (preg_match('/Bearer\s+(.*)$/i', $authHeader, $matches)) {
        return $matches[1];
    }
    
    return null;
}

/**
 * Require authentication (middleware)
 */
function requireAuth() {
    $token = getBearerToken() ?? ($_GET['token'] ?? '');
    
    if (empty($token)) {
        jsonResponse(false, 'Authentication required', null, 401);
    }
    
    $decoded = verifyToken($token);
    
    if (!$decoded) {
        jsonResponse(false, 'Invalid or expired token', null, 401);
    }
    
    return $decoded;
}

/**
 * Handle token refresh - issue new token if current is valid
 */
function handleRefreshToken() {
    $token = getBearerToken() ?? ($_GET['token'] ?? '');
    
    if (empty($token)) {
        jsonResponse(false, 'Token is required', null, 400);
    }
    
    $decoded = verifyToken($token);
    
    if (!$decoded) {
        jsonResponse(false, 'Invalid or expired token', null, 401);
    }
    
    // Generate new token with same user info
    $newToken = generateToken($decoded['user_id'], $decoded['role']);
    
    jsonResponse(true, 'Token refreshed successfully', [
        'token' => $newToken,
        'user_id' => $decoded['user_id'],
        'role' => $decoded['role']
    ]);
}
?>
