<?php
require_once '../db/config.php';
session_start();

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

$user_id = $_SESSION['user_id'];
$pdo = db();

// Handle Confirm Payment action
if (isset($_GET['action']) && $_GET['action'] === 'confirm_payment') {
    // Check for active order that is 'matched'
    $stmt = $pdo->prepare("SELECT id FROM fiat_orders WHERE user_id = ? AND status = 'matched' ORDER BY id DESC LIMIT 1");
    $stmt->execute([$user_id]);
    $order = $stmt->fetch();
    
    if (!$order) {
        echo json_encode(['success' => false, 'error' => '没有待确认的订单']);
        exit;
    }
    
    // Update status to submitting
    $stmt = $pdo->prepare("UPDATE fiat_orders SET status = 'submitting' WHERE id = ?");
    $stmt->execute([$order['id']]);
    
    // Send a system message to chat
    $pdo->prepare("INSERT INTO messages (user_id, sender, message) VALUES (?, 'user', '我已完成支付，请查收凭证。')")->execute([$user_id]);
    
    echo json_encode(['success' => true]);
    exit;
}

if (!isset($_FILES['image'])) {
    echo json_encode(['success' => false, 'error' => 'No image uploaded']);
    exit;
}

$file = $_FILES['image'];
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
$allowed = ['jpg', 'jpeg', 'png', 'gif'];

if (!in_array($ext, $allowed)) {
    echo json_encode(['success' => false, 'error' => 'Invalid file type']);
    exit;
}

$filename = 'chat_' . $user_id . '_' . time() . '_' . mt_rand(1000, 9999) . '.' . $ext;
$dir = '../assets/images/chat/';
if (!is_dir($dir)) mkdir($dir, 0775, true);

$target = $dir . $filename;

if (move_uploaded_file($file['tmp_name'], $target)) {
    $path = 'assets/images/chat/' . $filename;
    
    $stmt = $pdo->prepare("INSERT INTO messages (user_id, sender, type, message) VALUES (?, 'user', 'image', ?)");
    $stmt->execute([$user_id, $path]);
    
    // If there is an active order, update its proof_image
    $stmt = $pdo->prepare("SELECT id FROM fiat_orders WHERE user_id = ? AND status IN ('matched', 'matching', 'submitting') ORDER BY id DESC LIMIT 1");
    $stmt->execute([$user_id]);
    $order = $stmt->fetch();
    
    if ($order) {
        $stmt = $pdo->prepare("UPDATE fiat_orders SET proof_image = ? WHERE id = ?");
        $stmt->execute([$path, $order['id']]);
    }
    
    echo json_encode(['success' => true, 'path' => $path]);
} else {
    echo json_encode(['success' => false, 'error' => 'Failed to save image']);
}