<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/cwsn_validate.php';
requireLoginApi();
header('Content-Type: application/json');

$pdo = getPDO();
$role = currentRole();
$clrccode = currentClrcCode();

$isEdit = !empty($_POST['cwsn_code']);
$code = $isEdit ? $_POST['cwsn_code'] : null;

// ---- Permission check ----
if ($isEdit) {
    $stmt = $pdo->prepare('SELECT clrccode, status FROM cwsn WHERE cwsn_code = ?');
    $stmt->execute([$code]);
    $existing = $stmt->fetch();
    if (!$existing) { http_response_code(404); echo json_encode(['error' => 'Record not found.']); exit; }
    if ($role === 'clrc' && $existing['clrccode'] !== $clrccode) {
        http_response_code(403); echo json_encode(['error' => 'You can only manage records for your own CLRC.']); exit;
    }
} else {
    if ($role === 'clrc' && ($_POST['clrccode'] ?? '') !== $clrccode) {
        http_response_code(403); echo json_encode(['error' => 'You can only manage records for your own CLRC.']); exit;
    }
}

$fields = [
    'clrccode', 'clucd', 'cwsn_name', 'dob', 'gender', 'cwsn_f_name', 'cwsn_m_name', 'aadhaar',
    'add1', 'add2', 'add3', 'pin', 'contact_no', 'disability_id', 'dis_certi_yn', 'dis_certi_valid_yn',
    'appliance_id', 'therapy_reqd_yn', 'therapy_provide_yn', 'legalgurdian', 'manabik_yn', 'in_school_yn',
    'school_awc', 'schcd', 'awc_no', 'class', 'acno', 'ac_holder', 'bank_id', 'branch_name', 'micr', 'ifsc',
    'spledu_reg_no', 'date_of_entry', 'pen',
];
$data = [];
foreach ($fields as $f) {
    $v = trim((string)($_POST[$f] ?? ''));
    // Defense in depth: treat a literal "null" the same as blank. A client
    // bug could send this (e.g. JS serializing a real null into the text
    // "null" instead of an empty value) — never let that text reach a
    // column, especially a foreign key, as if it were real data.
    if ($v === '' || strcasecmp($v, 'null') === 0) { $data[$f] = null; continue; }
    $data[$f] = $v;
}

// Uppercase the same fields the original form auto-uppercased while typing.
foreach (['cwsn_name', 'cwsn_f_name', 'cwsn_m_name', 'legalgurdian', 'add1', 'add2', 'add3', 'ac_holder', 'ifsc'] as $f) {
    if ($data[$f] !== null) $data[$f] = strtoupper($data[$f]);
}
if ($data['aadhaar'] !== null) $data['aadhaar'] = preg_replace('/\D/', '', $data['aadhaar']);
if ($data['contact_no'] !== null) $data['contact_no'] = preg_replace('/\D/', '', $data['contact_no']);
if ($data['pin'] !== null) $data['pin'] = preg_replace('/\D/', '', $data['pin']);

// ---- Minimum bar for a brand-new record ----
if (!$isEdit) {
    if (empty($data['clrccode']) || empty($data['clucd']) || empty($data['cwsn_name'])) {
        http_response_code(422);
        echo json_encode(['error' => 'Please fill in CLRC, School/Cluster, and Name before the first save.']);
        exit;
    }
}

// ---- Validate (never blocks the save — only decides Complete vs Incomplete) ----
$errors = validateCwsn($data);
$isComplete = empty($errors);
$data = applyNotApplicableDefaults($data);

$existingStatus = $isEdit ? $existing['status'] : null;
$status = ($existingStatus === '1') ? '1' : ($isComplete ? '0' : '2'); // never resurrect a deleted record via a routine save

try {
    if ($isEdit) {
        $set = implode(', ', array_map(fn($f) => "$f = :$f", $fields));
        $sql = "UPDATE cwsn SET $set, status = :status WHERE cwsn_code = :cwsn_code";
        $stmt = $pdo->prepare($sql);
        $stmt->execute(array_merge($data, ['status' => $status, 'cwsn_code' => $code]));
    } else {
        // Simple unique code generator, matching the original app's pattern.
        $code = strtoupper($data['clrccode'] . '-' . base_convert((string)round(microtime(true) * 1000), 10, 36));
        $check = $pdo->prepare('SELECT 1 FROM cwsn WHERE cwsn_code = ?');
        $check->execute([$code]);
        if ($check->fetch()) {
            http_response_code(409);
            echo json_encode(['error' => 'A record with this CWSN code already exists — please try saving again.']);
            exit;
        }
        $cols = array_merge(['cwsn_code'], $fields, ['status']);
        $placeholders = implode(', ', array_map(fn($c) => ":$c", $cols));
        $sql = 'INSERT INTO cwsn (' . implode(', ', $cols) . ") VALUES ($placeholders)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute(array_merge($data, ['cwsn_code' => $code, 'status' => $status]));
    }

    echo json_encode([
        'ok' => true,
        'cwsn_code' => $code,
        'status' => $status,
        'complete' => $isComplete,
        'errors' => $errors,
    ]);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Could not save the record: ' . $e->getMessage()]);
}
