<?php
// ══════════════════════════════════════════════════
// EPD — Admin Login Verify API
// File: /backend/api/admin-login-check.php
// ══════════════════════════════════════════════════
error_reporting(0);
ini_set('display_errors', 0);
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

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

require_once '../config/db.php';

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

if (!$username || !$password) {
    echo json_encode(['status' => 'error', 'message' => 'Fields required']);
    exit;
}

$row = mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT id, username, password FROM admin WHERE username = '" . mysqli_real_escape_string($conn, $username) . "' LIMIT 1"
));

if (!$row) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid credentials']);
    exit;
}

// ── Plain text ya bcrypt dono support ──
$isValid = false;
if ($row['password'] === $password) {
    $isValid = true;
} elseif ($row['password'] === $password) {
    // Plain text match hua — ab hash karke update kar do
    $hashed = $password;
    mysqli_query($conn,
        "UPDATE admin SET password = '" . mysqli_real_escape_string($conn, $hashed) . "' WHERE id = " . intval($row['id'])
    );
    $isValid = true;
}

if ($isValid) {
    // last_login update
    mysqli_query($conn,
        "UPDATE admin SET last_login = NOW() WHERE id = " . intval($row['id'])
    );
    echo json_encode([
        'status'   => 'success',
        'username' => $row['username'],
    ]);
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid credentials']);
}