<?php
ini_set('display_errors', 0);
error_reporting(E_ALL);

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

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

function out_json($code, $success, $message, $data = null) {
    http_response_code($code);
    echo json_encode([
        'success' => (bool)$success,
        'status'  => (bool)$success,
        'message' => $message,
        'data'    => $data
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

if (function_exists('is_logged_in') && !is_logged_in()) {
    out_json(401, false, 'লগইন প্রয়োজন', null);
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    out_json(405, false, 'শুধু POST অনুরোধ গ্রহণযোগ্য', null);
}

if (!isset($pdo) || !($pdo instanceof PDO)) {
    out_json(500, false, 'Database connection পাওয়া যায়নি', null);
}

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

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

$name = trim((string)($data['account_name'] ?? $data['name'] ?? ''));
$type = trim((string)($data['account_type'] ?? $data['type'] ?? 'cash'));
$balance = (float)($data['opening_balance'] ?? $data['current_balance'] ?? $data['balance'] ?? 0);
$note = trim((string)($data['note'] ?? ''));

if ($name === '') {
    out_json(400, false, 'Account name দিন', null);
}

try {
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $tables = ['cash_accounts', 'accounts'];
    $table = null;

    foreach ($tables as $t) {
        $st = $pdo->prepare("SHOW TABLES LIKE ?");
        $st->execute([$t]);
        if ($st->fetchColumn()) {
            $table = $t;
            break;
        }
    }

    if (!$table) {
        out_json(500, false, 'cash_accounts/accounts table পাওয়া যায়নি', null);
    }

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

    $cols = [];
    foreach ($colsRaw as $c) {
        $cols[$c['Field']] = true;
    }

    $insert = [];
    $params = [];

    if (isset($cols['account_name'])) {
        $insert['account_name'] = $name;
    } elseif (isset($cols['name'])) {
        $insert['name'] = $name;
    } elseif (isset($cols['title'])) {
        $insert['title'] = $name;
    } else {
        out_json(500, false, 'Account name column পাওয়া যায়নি', null);
    }

    if (isset($cols['account_type'])) $insert['account_type'] = $type;
    elseif (isset($cols['type'])) $insert['type'] = $type;

    if (isset($cols['opening_balance'])) $insert['opening_balance'] = $balance;
    if (isset($cols['current_balance'])) $insert['current_balance'] = $balance;
    elseif (isset($cols['balance'])) $insert['balance'] = $balance;

    if (isset($cols['note'])) $insert['note'] = $note;
    elseif (isset($cols['description'])) $insert['description'] = $note;

    if (isset($cols['status'])) $insert['status'] = 'active';
    if (isset($cols['is_active'])) $insert['is_active'] = 1;

    if (isset($cols['created_at'])) $insert['created_at'] = date('Y-m-d H:i:s');
    if (isset($cols['updated_at'])) $insert['updated_at'] = date('Y-m-d H:i:s');

    $fieldNames = array_keys($insert);
    $placeholders = array_map(function($f){ return ':' . $f; }, $fieldNames);

    $sql = "INSERT INTO `$table` (`" . implode('`,`', $fieldNames) . "`) VALUES (" . implode(',', $placeholders) . ")";
    $stmt = $pdo->prepare($sql);

    foreach ($insert as $k => $v) {
        $stmt->bindValue(':' . $k, $v);
    }

    $stmt->execute();
    $id = (int)$pdo->lastInsertId();

    out_json(200, true, 'Account save হয়েছে', [
        'id' => $id,
        'account_id' => $id,
        'account_name' => $name,
        'name' => $name,
        'account_type' => $type,
        'current_balance' => $balance
    ]);

} catch (Throwable $e) {
    out_json(500, false, 'সার্ভার সমস্যা: ' . $e->getMessage(), null);
}