<?php
// Authentication endpoint for ESP32 devices and API access

switch ($method) {
    case 'POST':
        $data = json_decode(file_get_contents('php://input'), true);
        
        if (!isset($data['action'])) {
            http_response_code(400);
            echo json_encode(['error' => 'action is required']);
            break;
        }
        
        $action = $data['action'];
        
        switch ($action) {
            case 'login':
                // User login for API access
                if (!isset($data['email']) || !isset($data['password'])) {
                    http_response_code(400);
                    echo json_encode(['error' => 'email and password are required']);
                    break;
                }
                
                $email = $data['email'];
                $password = $data['password'];
                
                // Verify user credentials
                $stmt = $GLOBALS['con']->prepare("SELECT id, password FROM users WHERE email = ? AND deleted_at IS NULL");
                $stmt->bind_param("s", $email);
                $stmt->execute();
                $result = $stmt->get_result();
                
                if ($result->num_rows === 0) {
                    http_response_code(401);
                    echo json_encode(['error' => 'Invalid credentials']);
                    break;
                }
                
                $user = $result->fetch_assoc();
                
                if (!password_verify($password, $user['password'])) {
                    http_response_code(401);
                    echo json_encode(['error' => 'Invalid credentials']);
                    break;
                }
                
                // Generate API token
                $selector = bin2hex(random_bytes(16));
                $token = bin2hex(random_bytes(32));
                $hashed_token = password_hash($token, PASSWORD_DEFAULT);
                $expires_at = date('Y-m-d H:i:s', strtotime('+30 days'));
                
                // Store token
                $stmt = $GLOBALS['con']->prepare("
                    INSERT INTO auth_tokens (user_email, auth_type, selector, token, expires_at) 
                    VALUES (?, 'api', ?, ?, ?)
                ");
                $stmt->bind_param("ssss", $email, $selector, $hashed_token, $expires_at);
                
                if ($stmt->execute()) {
                    // Update last login
                    $stmt = $GLOBALS['con']->prepare("UPDATE users SET last_login_at = CURRENT_TIMESTAMP WHERE id = ?");
                    $stmt->bind_param("i", $user['id']);
                    $stmt->execute();
                    
                    echo json_encode([
                        'success' => true,
                        'token' => $selector . ':' . $token,
                        'expires_at' => $expires_at,
                        'user_id' => $user['id']
                    ]);
                } else {
                    http_response_code(500);
                    echo json_encode(['error' => 'Failed to generate token']);
                }
                break;
                
            case 'register_device':
                // Device registration (no auth required)
                if (!isset($data['device_id']) || !isset($data['user_email'])) {
                    http_response_code(400);
                    echo json_encode(['error' => 'device_id and user_email are required']);
                    break;
                }
                
                $device_id = $data['device_id'];
                $user_email = $data['user_email'];
                $device_name = $data['device_name'] ?? null;
                $device_type = $data['device_type'] ?? 'ESP32_ST7789_170x320';
                $screen_type = $data['screen_type'] ?? 'ST7789_170x320';
                
                // Verify user exists
                $stmt = $GLOBALS['con']->prepare("SELECT id FROM users WHERE email = ? AND deleted_at IS NULL");
                $stmt->bind_param("s", $user_email);
                $stmt->execute();
                $result = $stmt->get_result();
                
                if ($result->num_rows === 0) {
                    http_response_code(404);
                    echo json_encode(['error' => 'User not found']);
                    break;
                }
                
                $user_id = $result->fetch_assoc()['id'];
                
                // Check if device already exists
                $stmt = $GLOBALS['con']->prepare("SELECT id FROM devices WHERE device_id = ?");
                $stmt->bind_param("s", $device_id);
                $stmt->execute();
                $result = $stmt->get_result();
                
                if ($result->num_rows > 0) {
                    http_response_code(409);
                    echo json_encode(['error' => 'Device already registered']);
                    break;
                }
                
                // Insert new device
                $stmt = $GLOBALS['con']->prepare("
                    INSERT INTO devices (device_id, user_id, device_name, device_type, screen_type) 
                    VALUES (?, ?, ?, ?, ?)
                ");
                $stmt->bind_param("sisss", $device_id, $user_id, $device_name, $device_type, $screen_type);
                
                if ($stmt->execute()) {
                    $device_db_id = $stmt->insert_id;
                    
                    // Add owner permission
                    $stmt = $GLOBALS['con']->prepare("
                        INSERT INTO device_permissions (device_id, user_id, permission_type, granted_by) 
                        VALUES (?, ?, 'owner', ?)
                    ");
                    $stmt->bind_param("iii", $device_db_id, $user_id, $user_id);
                    $stmt->execute();
                    
                    echo json_encode(['success' => true, 'device_id' => $device_db_id]);
                } else {
                    http_response_code(500);
                    echo json_encode(['error' => 'Failed to register device']);
                }
                break;
                
            case 'device_auth':
                // Device authentication (for API access)
                if (!isset($data['device_id'])) {
                    http_response_code(400);
                    echo json_encode(['error' => 'device_id is required']);
                    break;
                }
                
                $device_id = $data['device_id'];
                
                // Verify device exists and get device info
                $stmt = $GLOBALS['con']->prepare("
                    SELECT d.*, u.email as owner_email 
                    FROM devices d 
                    JOIN users u ON d.user_id = u.id 
                    WHERE d.device_id = ?
                ");
                $stmt->bind_param("s", $device_id);
                $stmt->execute();
                $result = $stmt->get_result();
                
                if ($result->num_rows === 0) {
                    http_response_code(404);
                    echo json_encode(['error' => 'Device not found']);
                    break;
                }
                
                $device = $result->fetch_assoc();
                
                // Generate device token
                $selector = bin2hex(random_bytes(16));
                $token = bin2hex(random_bytes(32));
                $hashed_token = password_hash($token, PASSWORD_DEFAULT);
                $expires_at = date('Y-m-d H:i:s', strtotime('+365 days')); // Long-lived token for devices
                
                // Store device token
                $stmt = $GLOBALS['con']->prepare("
                    INSERT INTO auth_tokens (user_email, auth_type, selector, token, expires_at) 
                    VALUES (?, 'device', ?, ?, ?)
                ");
                $stmt->bind_param("ssss", $device['owner_email'], $selector, $hashed_token, $expires_at);
                
                if ($stmt->execute()) {
                    echo json_encode([
                        'success' => true,
                        'token' => $selector . ':' . $token,
                        'expires_at' => $expires_at,
                        'device_info' => [
                            'id' => $device['id'],
                            'device_id' => $device['device_id'],
                            'device_name' => $device['device_name'],
                            'device_type' => $device['device_type'],
                            'screen_type' => $device['screen_type'],
                            'profile_config' => $device['profile_config']
                        ]
                    ]);
                } else {
                    http_response_code(500);
                    echo json_encode(['error' => 'Failed to generate device token']);
                }
                break;
                
            default:
                http_response_code(400);
                echo json_encode(['error' => 'Invalid action']);
                break;
        }
        break;
        
    case 'DELETE':
        // Logout/revoke token
        $headers = getallheaders();
        $auth_header = $headers['Authorization'] ?? '';
        
        if (preg_match('/Bearer\s+(.*)$/', $auth_header, $matches)) {
            $token = $matches[1];
            
            // Delete token from database
            $stmt = $GLOBALS['con']->prepare("DELETE FROM auth_tokens WHERE token = ?");
            $stmt->bind_param("s", $token);
            
            if ($stmt->execute()) {
                echo json_encode(['success' => true]);
            } else {
                http_response_code(500);
                echo json_encode(['error' => 'Failed to revoke token']);
            }
        } else {
            http_response_code(400);
            echo json_encode(['error' => 'Authorization header required']);
        }
        break;
        
    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
        break;
}
?>
