<?php
// ════════════════════════════════════════════════════════
// SIMPLE AUTH API FOR TESTING
// Place in: Triangle_Tree_Life_Number/api/auth.php
// ════════════════════════════════════════════════════════

error_reporting(E_ALL);
ini_set('display_errors', 0); // Don't output errors (breaks JSON)

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Include database and helpers
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/config/helpers.php';

// Only handle POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['error' => 'Method not allowed']);
    exit();
}

// Get input
$input = json_decode(file_get_contents('php://input'), true);
$email = $input['email'] ?? '';
$password = $input['password'] ?? '';

if (empty($email) || empty($password)) {
    echo json_encode(['error' => 'Email and password required']);
    exit();
}

try {
    // Find user
    $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ? AND is_active = 1");
    $stmt->execute([$email]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$user) {
        echo json_encode(['error' => 'Invalid credentials']);
        exit();
    }
    
    // Verify password
    if (!password_verify($password, $user['password'])) {
        echo json_encode(['error' => 'Invalid credentials']);
        exit();
    }
    
    // Generate JWT token
    $jwtSecret = getenv('JWT_SECRET') ?: 'default_secret_change_this';
    $sessionToken = bin2hex(random_bytes(16));
    
    $payload = [
        'userId' => $user['id'],
        'email' => $user['email'],
        'role' => $user['role'],
        'st' => $sessionToken
    ];
    
    // Create JWT token (expires in 7 days)
    $accessToken = createJWT($payload, $jwtSecret, '7d');
    
    // Update session token in database
    $stmt = $pdo->prepare("UPDATE users SET session_token = ?, last_login = NOW() WHERE id = ?");
    $stmt->execute([$sessionToken, $user['id']]);
    
    // Return success
    echo json_encode([
        'success' => true,
        'accessToken' => $accessToken,
        'user' => [
            'id' => $user['id'],
            'name' => $user['name'],
            'email' => $user['email'],
            'role' => $user['role']
        ]
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'error' => 'Login failed',
        'message' => $e->getMessage()
    ]);
}
?>
