<?php
header('Content-Type: application/json; charset=utf-8');
require_once '../db.php';

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'กรุณาเข้าสู่ระบบก่อน']);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];
$userId = (int)$_SESSION['user_id'];
$userRole = $_SESSION['role'] ?? 'buyer';

// ---- GET: check current application status ----
if ($method === 'GET') {
    $stmt = $conn->prepare("SELECT application_id, shop_name, status, applied_at FROM seller_applications WHERE user_id = ? ORDER BY applied_at DESC LIMIT 1");
    $stmt->bind_param('i', $userId);
    $stmt->execute();
    $result = $stmt->get_result();
    $app = $result->fetch_assoc();
    $stmt->close();
    echo json_encode(['success' => true, 'application' => $app, 'role' => $userRole]);
    exit;
}

// ---- POST: submit new application ----
if ($method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    $shopName = trim($input['shop_name'] ?? '');
    $description = trim($input['description'] ?? '');
    $phone = trim($input['phone'] ?? '');
    $address = trim($input['address'] ?? '');

    if (empty($shopName)) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'กรุณากรอกชื่อร้านค้า']);
        exit;
    }

    // Check if already has pending/approved application
    $check = $conn->prepare("SELECT status FROM seller_applications WHERE user_id = ? ORDER BY applied_at DESC LIMIT 1");
    $check->bind_param('i', $userId);
    $check->execute();
    $existing = $check->get_result()->fetch_assoc();
    $check->close();

    if ($existing && in_array($existing['status'], ['pending', 'approved'])) {
        http_response_code(409);
        echo json_encode(['success' => false, 'message' => 'คุณมีคำขอที่กำลังรอการพิจารณาหรือได้รับการอนุมัติแล้ว']);
        exit;
    }

    $stmt = $conn->prepare("INSERT INTO seller_applications (user_id, shop_name, status) VALUES (?, ?, 'pending')");
    $stmt->bind_param('is', $userId, $shopName);
    if ($stmt->execute()) {
        $appId = $conn->insert_id;
        $stmt->close();
        echo json_encode(['success' => true, 'message' => 'ส่งคำขอสมัครผู้ขายเรียบร้อย อยู่ระหว่างการพิจารณา', 'application_id' => $appId]);
    } else {
        $stmt->close();
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'เกิดข้อผิดพลาด กรุณาลองใหม่']);
    }
    exit;
}

http_response_code(405);
echo json_encode(['success' => false, 'message' => 'Method Not Allowed']);
?>
