<?php
/**
 * Quick Add Party API
 * POST: name, phone, address, note, is_customer, is_supplier, is_pledge, 
 *       is_karigar, is_locker, opening_receivable, opening_payable, force_create
 */
require_once __DIR__ . '/../_core.php';
header('Content-Type: application/json; charset=utf-8');

if (!is_logged_in()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'লগইন প্রয়োজন']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'POST only']);
    exit;
}

try {
    // JSON ও form দুটোই গ্রহণ করে
    $input = $_POST;
    if (empty($input)) {
        $json  = file_get_contents('php://input');
        $input = json_decode($json, true) ?: [];
    }

    $name    = trim($input['name']    ?? '');
    $phone   = trim($input['phone']   ?? '');
    $address = trim($input['address'] ?? '');
    $note    = trim($input['note']    ?? '');

    $is_customer = !empty($input['is_customer']) ? 1 : 0;
    $is_supplier = !empty($input['is_supplier']) ? 1 : 0;
    $is_pledge   = !empty($input['is_pledge'])   ? 1 : 0;
    $is_karigar  = !empty($input['is_karigar'])  ? 1 : 0;
    $is_locker   = !empty($input['is_locker'])   ? 1 : 0;

    $opening_receivable = (float)($input['opening_receivable'] ?? 0);
    $opening_payable    = (float)($input['opening_payable']    ?? 0);
    $force_create       = !empty($input['force_create']) ? 1 : 0;

    // Validation
    if ($name === '') {
        echo json_encode(['success' => false, 'message' => '⚠️ নাম দিতে হবে']);
        exit;
    }

    if (($is_customer + $is_supplier + $is_pledge + $is_karigar + $is_locker) === 0) {
        echo json_encode(['success' => false, 'message' => '⚠️ অন্তত একটি role নির্বাচন করুন']);
        exit;
    }

    // Duplicate check (phone থাকলে)
    if ($phone !== '' && !$force_create) {
        $check = $pdo->prepare("
            SELECT id, name, phone, address,
                   is_customer, is_supplier, is_pledge, is_karigar, is_locker
            FROM parties 
            WHERE phone = :phone AND deleted_at IS NULL 
            LIMIT 1
        ");
        $check->execute([':phone' => $phone]);
        $existing = $check->fetch(PDO::FETCH_ASSOC);
        
        if ($existing) {
            echo json_encode([
                'success'   => false,
                'duplicate' => true,
                'message'   => "⚠️ এই ফোন নম্বরে party আছে: {$existing['name']}",
                'existing'  => $existing
            ], JSON_UNESCAPED_UNICODE);
            exit;
        }
    }

    // Insert
    $sql = "INSERT INTO parties 
                (name, phone, address, note,
                 is_customer, is_supplier, is_pledge, is_karigar, is_locker,
                 opening_receivable, opening_payable, balance, gold_balance, created_at)
            VALUES 
                (:name, :phone, :address, :note,
                 :is_customer, :is_supplier, :is_pledge, :is_karigar, :is_locker,
                 :op_rec, :op_pay, 0, 0, NOW())";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':name'        => $name,
        ':phone'       => $phone,
        ':address'     => $address,
        ':note'        => $note,
        ':is_customer' => $is_customer,
        ':is_supplier' => $is_supplier,
        ':is_pledge'   => $is_pledge,
        ':is_karigar'  => $is_karigar,
        ':is_locker'   => $is_locker,
        ':op_rec'      => $opening_receivable,
        ':op_pay'      => $opening_payable,
    ]);

    $new_id = (int)$pdo->lastInsertId();
    $get = $pdo->prepare("SELECT * FROM parties WHERE id = :id");
    $get->execute([':id' => $new_id]);
    $party = $get->fetch(PDO::FETCH_ASSOC);

    echo json_encode([
        'success' => true,
        'message' => "✅ নতুন party যোগ হয়েছে: {$name}",
        'party'   => $party
    ], JSON_UNESCAPED_UNICODE);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'সার্ভার ত্রুটি: ' . $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
}