<?php
/**
 * File: api/karigar/update_karigar.php
 * Purpose: Karigar info update (নাম/ফোন/ঠিকানা/নোট/opening_payable)
 * Method : POST
 * Input  : { id, name, phone, address, note, opening_payable }
 * Note   : Destructive নয় — শুধু parties row update
 * 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;

$id              = (int)($data['id'] ?? 0);
$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 ($id <= 0) {
    out_json(400, false, 'Karigar ID দিন', null);
}
if ($name === '') {
    out_json(400, false, 'নাম খালি রাখা যাবে না', null);
}

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

    // ===== Existence check =====
    $chk = $pdo->prepare("SELECT id, name, phone, address, note, opening_payable, is_karigar
                          FROM `parties` WHERE id = ? LIMIT 1");
    $chk->execute([$id]);
    $old = $chk->fetch(PDO::FETCH_ASSOC);

    if (!$old) {
        out_json(404, false, 'এই ID-র karigar পাওয়া যায়নি', null);
    }
    if ((int)$old['is_karigar'] !== 1) {
        out_json(400, false, 'এই party karigar হিসেবে mark করা নেই', null);
    }

    // ===== Phone duplicate check (অন্য row এ থাকলে) =====
    if ($phone !== '' && $phone !== (string)$old['phone']) {
        $dup = $pdo->prepare("SELECT id, name FROM `parties` WHERE phone = ? AND id != ? LIMIT 1");
        $dup->execute([$phone, $id]);
        $exist = $dup->fetch(PDO::FETCH_ASSOC);

        if ($exist) {
            out_json(409, false, 'এই ফোনে আগে থেকেই party আছে: ' . $exist['name'], null);
        }
    }

    // ===== Update =====
    $upd = $pdo->prepare("
        UPDATE `parties`
        SET name = :name,
            phone = :phone,
            address = :address,
            note = :note,
            opening_payable = :opening_payable
        WHERE id = :id
    ");
    $upd->execute([
        ':name'            => $name,
        ':phone'           => ($phone === '' ? null : $phone),
        ':address'         => $address,
        ':note'            => $note,
        ':opening_payable' => $opening_payable,
        ':id'              => $id
    ]);

    // ===== Audit log =====
    try {
        $log = $pdo->prepare("
            INSERT INTO audit_log
                (table_name, record_id, action, changed_by, changed_at, ip_address, old_values, new_values, note)
            VALUES
                ('parties', ?, 'UPDATE', ?, NOW(), ?, ?, ?, 'Karigar info update')
        ");
        $log->execute([
            $id,
            (int)($_SESSION['user_id'] ?? 0),
            $_SERVER['REMOTE_ADDR'] ?? '',
            json_encode($old, JSON_UNESCAPED_UNICODE),
            json_encode([
                'name' => $name, 'phone' => $phone, 'address' => $address,
                'note' => $note, 'opening_payable' => $opening_payable
            ], JSON_UNESCAPED_UNICODE)
        ]);
    } catch (Throwable $e) { /* audit fail silent */ }

    out_json(200, true, 'Karigar info update হলো', [
        'id'              => $id,
        'name'            => $name,
        'phone'           => $phone,
        'address'         => $address,
        'note'            => $note,
        'opening_payable' => $opening_payable
    ]);

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