<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);

header('Content-Type: application/json; charset=utf-8');

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

function out($success, $message, $data = [], $status = 200)
{
    http_response_code($status);
    echo json_encode([
        'success' => $success,
        'message' => $message,
        'data' => $data
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

function table_exists(PDO $pdo, $table)
{
    $stmt = $pdo->prepare("
        SELECT COUNT(*)
        FROM information_schema.tables
        WHERE table_schema = DATABASE() AND table_name = ?
    ");
    $stmt->execute([$table]);
    return (int)$stmt->fetchColumn() > 0;
}

function get_column_names(PDO $pdo, $table)
{
    if (!table_exists($pdo, $table)) return [];

    $stmt = $pdo->query("SHOW COLUMNS FROM `$table`");
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    return array_map(function ($r) {
        return $r['Field'];
    }, $rows);
}

function append_note($oldNote, $newText)
{
    $oldNote = trim((string)$oldNote);
    $newText = trim((string)$newText);

    if ($newText === '') {
        return $oldNote;
    }

    if ($oldNote === '') {
        return $newText;
    }

    return $oldNote . "\n" . $newText;
}

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        out(false, 'Invalid request method', [], 405);
    }

    $raw = file_get_contents('php://input');
    $input = json_decode($raw, true);

    if (!is_array($input)) {
        $input = $_POST;
    }

    if (!is_array($input)) {
        out(false, 'Invalid request data', [], 400);
    }

    $pledge_id = (int)($input['pledge_id'] ?? 0);
    $note = trim($input['note'] ?? '');

    if ($pledge_id <= 0) {
        out(false, 'সঠিক pledge id দিন', [], 400);
    }

    if (!table_exists($pdo, 'pawn_pledges')) {
        out(false, 'pawn_pledges table পাওয়া যায়নি', [], 500);
    }

    $cols = get_column_names($pdo, 'pawn_pledges');

    $selectFields = ['id', 'pledge_code', 'status', 'holding_status'];
    if (in_array('note', $cols, true)) {
        $selectFields[] = 'note';
    }

    $sql = "SELECT " . implode(', ', $selectFields) . " FROM pawn_pledges WHERE id = ? LIMIT 1";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([$pledge_id]);
    $pledge = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$pledge) {
        out(false, 'Pledge পাওয়া যায়নি', [], 404);
    }

    $currentStatus = strtoupper((string)($pledge['status'] ?? 'OPEN'));
    $currentHolding = strtoupper((string)($pledge['holding_status'] ?? 'SHOWROOM'));

    if ($currentStatus === 'CLOSED') {
        out(false, 'Closed pledge locker-এ transfer করা যাবে না', [], 400);
    }

    if ($currentHolding === 'LOCKER') {
        out(true, 'Pledge আগেই locker-এ আছে', [
            'pledge_id' => (int)$pledge['id'],
            'pledge_code' => $pledge['pledge_code'] ?? '',
            'holding_status' => 'LOCKER'
        ]);
    }

    $updateParts = [];
    $params = [];

    if (in_array('holding_status', $cols, true)) {
        $updateParts[] = "holding_status = ?";
        $params[] = 'LOCKER';
    } else {
        out(false, 'holding_status column পাওয়া যায়নি', [], 500);
    }

    if (in_array('updated_at', $cols, true)) {
        $updateParts[] = "updated_at = NOW()";
    }

    if (in_array('locker_transferred_at', $cols, true)) {
        $updateParts[] = "locker_transferred_at = NOW()";
    }

    if (in_array('note', $cols, true)) {
        $autoText = 'Transferred to LOCKER on ' . date('Y-m-d H:i:s');
        if ($note !== '') {
            $autoText .= ' | ' . $note;
        }

        $newNote = append_note($pledge['note'] ?? '', $autoText);
        $updateParts[] = "note = ?";
        $params[] = $newNote;
    }

    $params[] = $pledge_id;

    $updateSql = "UPDATE pawn_pledges SET " . implode(', ', $updateParts) . " WHERE id = ?";

    $pdo->beginTransaction();

    $stmt = $pdo->prepare($updateSql);
    $stmt->execute($params);

    $pdo->commit();

    out(true, 'Pledge successfully transferred to locker', [
        'pledge_id' => (int)$pledge['id'],
        'pledge_code' => $pledge['pledge_code'] ?? '',
        'holding_status' => 'LOCKER'
    ]);

} catch (Throwable $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }

    out(false, 'Server error: ' . $e->getMessage(), [], 500);
}