<?php
// ============================================================
// api/auth.php
// Includes DB config directly — same server, no HTTP needed
// ============================================================
session_start();
header('Content-Type: application/json');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: Thu, 01 Jan 1970 00:00:00 GMT');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

// Direct DB connection — same credentials as api.php in public_html root
// On same server, PDO to external host works from root but may be blocked in subfolders
// So we use the SAME connection string but via include path trick
$host = 'database.xhost.co.in';
$db   = 'db_iqpj6ze2cf';
$user = 'db_iqpj6ze2cf';
$pass = 'O*9Mp;%5PPDyv8oD';

function getPdo() {
    global $host, $db, $user, $pass;
    static $pdo = null;
    if ($pdo) return $pdo;
    try {
        $pdo = new PDO("pgsql:host=$host;port=5432;dbname=$db", $user, $pass, [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_TIMEOUT            => 10,
        ]);
        return $pdo;
    } catch (PDOException $e) {
        http_response_code(500);
        echo json_encode(['status' => 'error', 'msg' => 'DB failed: ' . $e->getMessage()]);
        exit;
    }
}

$input  = json_decode(file_get_contents('php://input'), true) ?? [];
$action = $input['action'] ?? $_GET['action'] ?? '';

switch ($action) {

    case 'login':
        $username = trim(strtolower($input['username'] ?? ''));
        $password = $input['password'] ?? '';
        if (!$username || !$password) {
            echo json_encode(['status' => 'error', 'msg' => 'Username and password required']); exit;
        }
        try {
            $stmt = getPdo()->prepare("SELECT * FROM agent_users WHERE LOWER(username) = ? AND is_active = true LIMIT 1");
            $stmt->execute([$username]);
            $row = $stmt->fetch();
            if (!$row || !password_verify($password, $row['password_hash'])) {
                echo json_encode(['status' => 'error', 'msg' => 'Invalid username or password']); exit;
            }
            // Normalize all string values to prevent whitespace issues
    $_SESSION['oms_user'] = [
                'id'       => $row['id'],
                'username' => $row['username'],
                'name'     => $row['name'],
                'role'     => $row['role'],
            ];
            echo json_encode(['status' => 'success', 'user' => [
                'name' => $row['name'], 'username' => $row['username'], 'role' => $row['role']
            ]]);
        } catch (PDOException $e) {
            echo json_encode(['status' => 'error', 'msg' => $e->getMessage()]);
        }
        break;

    case 'logout':
        session_destroy();
        echo json_encode(['status' => 'success']);
        break;

    case 'me':
        if (!isset($_SESSION['oms_user'])) {
            http_response_code(401); echo json_encode(['status' => 'error', 'msg' => 'Not logged in']); exit;
        }
        echo json_encode(['status' => 'success', 'user' => $_SESSION['oms_user']]);
        break;

    default:
        http_response_code(400);
        echo json_encode(['status' => 'error', 'msg' => 'Unknown action: ' . $action]);
}
