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

$d    = json_decode(file_get_contents('php://input'), true);
$name = trim($d['name'] ?? '');
$rate = (float)($d['monthly_rent_rate'] ?? 4);

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

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

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

    /* পার্টি থাকলে is_locker=1 করুন */
    if ($party_id) {
        $pdo->prepare("UPDATE parties SET is_locker=1 WHERE id=?")->execute([$party_id]);
    }

    echo json_encode(['success'=>true,'message'=>'লকার যোগ হয়েছে','id'=>$pdo->lastInsertId()]);
} catch (Exception $e) {
    echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
}