<?php
/**
 * File: api/karigar/add_karigar.php
 * Purpose: নতুন karigar add (parties এ is_karigar=1 সহ)
 * Method : POST
 * Input  : { name, phone, address, note, opening_payable }
 * Output : { success, message, data: { id, name, phone, ... } }
 * Date   : 2026-05-27
 */

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'] ?? ''));
$phone            = trim((string)($data['phone'] ?? ''));
$address          = trim((string)($data['address'] ?? ''));
$note             = trim((string)($data['note'] ?? ''));
$opening_payable  = (float)($data['opening_payable'] ?? 0);

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

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

    // ===== Duplicate phone check (যদি phone থাকে) =====
    if ($phone !== '') {
        $dup = $pdo->prepare("SELECT id, name, is_karigar FROM `parties` WHERE phone = ? LIMIT 1");
        $dup->execute([$phone]);
        $exist = $dup->fetch(PDO::FETCH_ASSOC);

        if ($exist) {
            // যদি already exists কিন্তু is_karigar=0 — শুধু flag update করি
            if ((int)$exist['is_karigar'] === 0) {
                $upd = $pdo->prepare("UPDATE `parties` SET is_karigar = 1 WHERE id = ?");
                $upd->execute([(int)$exist['id']]);

                out_json(200, true, 'এই ফোনের পার্টি আগেই ছিল — karigar হিসেবে mark করা হলো', [
                    'id'   => (int)$exist['id'],
                    'name' => (string)$exist['name'],
                    'phone'=> $phone,
                    'is_existing' => true
                ]);
            } else {
                out_json(409, false, 'এই ফোনে আগে থেকেই karigar আছে: ' . $exist['name'], [
                    'id' => (int)$exist['id']
                ]);
            }
        }
    }

    // ===== Insert new karigar =====
    $sql = "INSERT INTO `parties`
            (name, phone, address, balance, created_at,
             is_customer, is_supplier, is_pledge, is_locker, is_karigar,
             gold_balance, note, opening_receivable, opening_payable)
            VALUES
            (:name, :phone, :address, 0.00, NOW(),
             0, 0, 0, 0, 1,
             0.000, :note, 0.00, :opening_payable)";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':name'            => $name,
        ':phone'           => ($phone === '' ? null : $phone),
        ':address'         => $address,
        ':note'            => $note,
        ':opening_payable' => $opening_payable
    ]);

    $newId = (int)$pdo->lastInsertId();

    // ===== Audit log =====
    try {
        $log = $pdo->prepare("
            INSERT INTO audit_log
                (table_name, record_id, action, changed_by, changed_at, ip_address, new_values, note)
            VALUES
                ('parties', ?, 'INSERT', ?, NOW(), ?, ?, 'New karigar added')
        ");
        $log->execute([
            $newId,
            (int)($_SESSION['user_id'] ?? 0),
            $_SERVER['REMOTE_ADDR'] ?? '',
            json_encode([
                'name' => $name, 'phone' => $phone, 'is_karigar' => 1
            ], JSON_UNESCAPED_UNICODE)
        ]);
    } catch (Throwable $e) { /* audit fail silent */ }

    out_json(200, true, 'নতুন Karigar সফলভাবে add হলো', [
        'id'              => $newId,
        'name'            => $name,
        'phone'           => $phone,
        'address'         => $address,
        'note'            => $note,
        'opening_payable' => $opening_payable,
        'is_existing'     => false
    ]);

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