<?php
/**
 * CinemaHD52 - Local Panel Login (APK fallback)
 *
 * Upload to: /public_html/cinemahd52/api/local_login.php
 * Uses DB:   /public_html/cinemahd52/api/.db.db
 */

date_default_timezone_set('UTC');
header('Content-Type: application/json; charset=UTF-8');

function respond(array $user_info): void {
    http_response_code(200);
    echo json_encode(['user_info' => $user_info], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    exit;
}

$username = isset($_GET['username']) ? trim((string)$_GET['username']) : '';
$password = isset($_GET['password']) ? trim((string)$_GET['password']) : '';

if ($username === '' || $password === '') {
    respond(['auth' => 0, 'message' => 'Missing credentials']);
}

$db = new SQLite3(__DIR__ . '/.db.db');

// Ensure table exists (compatible with the CinemaHD52 panel)
$db->exec("CREATE TABLE IF NOT EXISTS extra_accounts (
    id INTEGER PRIMARY KEY,
    username TEXT NOT NULL UNIQUE,
    password TEXT NOT NULL,
    status TEXT NOT NULL,
    expiry TEXT NOT NULL
);");

$stmt = $db->prepare('SELECT username, password, status, expiry FROM extra_accounts WHERE username = :u LIMIT 1');
$stmt->bindValue(':u', $username, SQLITE3_TEXT);
$row = $stmt->execute()->fetchArray(SQLITE3_ASSOC);

if (!$row) {
    respond(['auth' => 0, 'message' => 'Invalid username or password']);
}

// Status check (support both 'Active' and '1')
$status_ok = ($row['status'] === 'Active' || $row['status'] === '1' || $row['status'] === 1);

// Expiry check (support unix timestamp or date string; allow empty = never)
$expiry_ok = true;
if (!empty($row['expiry'])) {
    if (is_numeric($row['expiry'])) {
        $expiry_ok = ((int)$row['expiry'] > time());
    } else {
        $t = strtotime($row['expiry']);
        $expiry_ok = ($t !== false && $t > time());
    }
}

if (!$status_ok || !$expiry_ok || !hash_equals((string)$row['password'], $password)) {
    respond(['auth' => 0, 'message' => 'Invalid username or password']);
}

// Success: return the exact keys the APK parser expects
respond([
    'username' => $row['username'],
    'password' => $row['password'],
    'auth' => 1,
    'status' => 'Active',
    'message' => 'Login successful!'
]);
