<?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['name'] ?? $data['party_name'] ?? $data['customer_name'] ?? ''));
$phone = trim((string)($data['phone'] ?? $data['mobile'] ?? $data['customer_phone'] ?? ''));
$address = trim((string)($data['address'] ?? $data['note'] ?? ''));
$type = trim((string)($data['party_type'] ?? $data['type'] ?? 'customer'));

if ($name === '') {
    out_json(400, false, 'পার্টির নাম দিন', null);
}

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

    $st = $pdo->prepare("SHOW TABLES LIKE 'parties'");
    $st->execute();

    if (!$st->fetchColumn()) {
        out_json(500, false, 'parties table পাওয়া যায়নি', null);
    }

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

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

    if ($phone !== '') {
        $phoneCol = null;

        if (isset($cols['phone'])) $phoneCol = 'phone';
        elseif (isset($cols['mobile'])) $phoneCol = 'mobile';
        elseif (isset($cols['contact'])) $phoneCol = 'contact';

        if ($phoneCol) {
            $dup = $pdo->prepare("SELECT id FROM `parties` WHERE `$phoneCol` = ? LIMIT 1");
            $dup->execute([$phone]);
            $oldId = $dup->fetchColumn();

            if ($oldId) {
                out_json(200, true, 'এই মোবাইলের পার্টি আগে থেকেই আছে', [
                    'id' => (int)$oldId,
                    'party_id' => (int)$oldId,
                    'name' => $name,
                    'phone' => $phone
                ]);
            }
        }
    }

    $insert = [];

    if (isset($cols['name'])) $insert['name'] = $name;
    elseif (isset($cols['party_name'])) $insert['party_name'] = $name;
    elseif (isset($cols['customer_name'])) $insert['customer_name'] = $name;
    else out_json(500, false, 'Name column পাওয়া যায়নি', null);

    if (isset($cols['phone'])) $insert['phone'] = $phone;
    elseif (isset($cols['mobile'])) $insert['mobile'] = $phone;
    elseif (isset($cols['contact'])) $insert['contact'] = $phone;

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

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

    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 `parties` (`" . 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, 'পার্টি save হয়েছে', [
        'id' => $id,
        'party_id' => $id,
        'name' => $name,
        'phone' => $phone
    ]);

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