<?php
require_once '../_core.php';
is_logged_in();

$d  = json_decode(file_get_contents('php://input'), true);
$id = (int)($d['id'] ?? 0);

if (!$id) { echo json_encode(['success'=>false,'message'=>'ID দিন']); exit; }

$party_id = !empty($d['party_id']) ? (int)$d['party_id'] : null;
$name     = trim($d['name'] ?? '');
$phone    = trim($d['phone'] ?? '');
$address  = trim($d['address'] ?? '');
$rate     = (float)($d['monthly_rent_rate'] ?? 4);
$bal      = (float)($d['opening_balance'] ?? 0);
$status   = in_array($d['status']??'active', ['active','inactive']) ? $d['status'] : 'active';
$notes    = trim($d['notes'] ?? '');

if (!$name) { echo json_encode(['success'=>false,'message'=>'নাম দিন']); exit; }

try {
    $stmt = $pdo->prepare("UPDATE lockers SET party_id=?, name=?, phone=?, address=?, monthly_rent_rate=?, opening_balance=?, status=?, notes=? WHERE id=?");
    $stmt->execute([$party_id, $name, $phone, $address, $rate, $bal, $status, $notes, $id]);

    if ($party_id) {
        $pdo->prepare("UPDATE parties SET is_locker=1 WHERE id=?")->execute([$party_id]);
    }

    echo json_encode(['success'=>true,'message'=>'আপডেট হয়েছে']);
} catch (Exception $e) {
    echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
}