<?php
/**
 * Auth API Endpoint
 * Handles user login, registration, and user accounts list in MySQL.
 */

require_once __DIR__ . '/db.php';

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? 'login';

if ($method === 'GET') {
    if ($action === 'accounts') {
        // List all accounts (e.g., for admin management)
        $stmt = $pdo->query("SELECT id, email, full_name, role, status, phone, store_type, logo, avatar_url, DATE_FORMAT(created_at, '%d/%m/%Y') as date FROM users ORDER BY created_at DESC");
        $users = $stmt->fetchAll();
        $formatted = array_map(function($u) {
            return [
                'id'        => $u['id'],
                'email'     => $u['email'],
                'fullName'  => $u['full_name'],
                'role'      => $u['role'],
                'status'    => $u['status'],
                'phone'     => $u['phone'],
                'storeType' => $u['store_type'],
                'logo'      => $u['logo'],
                'date'      => $u['date']
            ];
        }, $users);
        sendResponse(true, $formatted, 'ดึงรายชื่อผู้ใช้งานสำเร็จ');
    }
}

if ($method === 'POST') {
    $body = getJsonInput();

    if ($action === 'register') {
        $email = trim(strtolower($body['email'] ?? ''));
        $fullName = trim($body['fullName'] ?? '');
        $phone = trim($body['phone'] ?? '');
        $role = $body['role'] ?? 'customer';
        $storeType = $body['storeType'] ?? null;
        $logo = $body['logo'] ?? null;
        $password = $body['password'] ?? '123456';

        if (empty($email) || empty($fullName) || empty($phone)) {
            sendResponse(false, null, 'กรุณากรอกข้อมูลให้ครบถ้วน', 400);
        }

        // Check duplicates
        $stmt = $pdo->prepare("SELECT id FROM users WHERE email = :email OR phone = :phone LIMIT 1");
        $stmt->execute([':email' => $email, ':phone' => $phone]);
        if ($stmt->fetch()) {
            sendResponse(false, null, 'อีเมลหรือเบอร์โทรนี้ถูกใช้งานแล้ว', 409);
        }

        $id = 'usr_' . rand(1000, 9999);
        $status = $role === 'customer' ? 'approved' : 'pending';
        $passwordHash = password_hash($password, PASSWORD_DEFAULT);

        $stmt = $pdo->prepare("INSERT INTO users (id, email, password_hash, full_name, role, status, phone, store_type, logo, created_at)
                               VALUES (:id, :email, :pass, :name, :role, :status, :phone, :stype, :logo, NOW())");
        $stmt->execute([
            ':id'     => $id,
            ':email'  => $email,
            ':pass'   => $passwordHash,
            ':name'   => $fullName,
            ':role'   => $role,
            ':status' => $status,
            ':phone'  => $phone,
            ':stype'  => $storeType,
            ':logo'   => $logo
        ]);

        sendResponse(true, [
            'id'       => $id,
            'email'    => $email,
            'fullName' => $fullName,
            'role'     => $role,
            'status'   => $status,
            'phone'    => $phone,
            'date'     => date('d/m/Y')
        ], 'ลงทะเบียนสำเร็จ');
    }

    if ($action === 'login') {
        $email = trim(strtolower($body['email'] ?? ''));
        $password = $body['password'] ?? '';

        if (empty($email)) {
            sendResponse(false, null, 'กรุณากรอกอีเมล', 400);
        }

        // Admin fast fallback / alias
        if (in_array($email, ['admin@cmtc.ac.th', 'admin@cm.ac.th', 'admin'])) {
            sendResponse(true, [
                'id'       => 'usr_admin',
                'email'    => 'admin@cmtc.ac.th',
                'fullName' => 'ผู้ดูแลระบบส่วนกลาง (Admin)',
                'role'     => 'admin',
                'token'    => 'jwt_admin_' . time()
            ], 'เข้าสู่ระบบสำเร็จ');
        }

        $stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email LIMIT 1");
        $stmt->execute([':email' => $email]);
        $user = $stmt->fetch();

        if (!$user) {
            sendResponse(false, null, 'อีเมลนี้ยังไม่ได้ลงทะเบียนในระบบ', 404);
        }

        if ($user['status'] === 'pending') {
            sendResponse(false, null, 'บัญชีของคุณกำลังรอการอนุมัติจากแอดมิน', 403);
        }

        sendResponse(true, [
            'id'        => $user['id'],
            'email'     => $user['email'],
            'fullName'  => $user['full_name'],
            'role'      => $user['role'],
            'phone'     => $user['phone'],
            'avatarUrl' => $user['avatar_url'],
            'token'     => 'jwt_' . $user['id'] . '_' . time()
        ], 'เข้าสู่ระบบสำเร็จ');
    }
}
