<?php
/**
 * POST /api/app/attendance/record
 */
require_once __DIR__ . '/../../bootstrap.php';
requireApiPermission('attendance.record');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true) ?: [];
$serviceTypeId = (int) ($data['service_type_id'] ?? 0);
$date = isset($data['date']) ? trim((string) $data['date']) : '';
if ($serviceTypeId <= 0 || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
    http_response_code(400);
    echo json_encode(['error' => 'service_type_id and date (YYYY-MM-DD) required']);
    exit;
}

$male = max(0, (int) ($data['male_count'] ?? 0));
$female = max(0, (int) ($data['female_count'] ?? 0));
$children = max(0, (int) ($data['children_count'] ?? 0));
$visitors = max(0, (int) ($data['visitors_count'] ?? 0));
$notes = isset($data['notes']) && $data['notes'] !== '' ? trim((string) $data['notes']) : null;

try {
    $stmt = $pdo->prepare('SELECT id FROM attendance_records WHERE service_type_id = ? AND date = ?');
    $stmt->execute([$serviceTypeId, $date]);
    $row = $stmt->fetch();
    if ($row) {
        $pdo->prepare('UPDATE attendance_records SET male_count=?, female_count=?, children_count=?, visitors_count=?, notes=? WHERE id=?')
            ->execute([$male, $female, $children, $visitors, $notes, $row['id']]);
    } else {
        $pdo->prepare('INSERT INTO attendance_records (service_type_id, date, male_count, female_count, children_count, visitors_count, notes) VALUES (?,?,?,?,?,?,?)')
            ->execute([$serviceTypeId, $date, $male, $female, $children, $visitors, $notes]);
    }
    echo json_encode(['ok' => true]);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Failed to save']);
}
