<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/_admin_auth.php';

golder_require_method('POST');
golder_api_admin_auth();
$master = golder_master_pdo();
$input = golder_api_input();

$customerId = (int)($input['customer_id'] ?? 0);
$planType = trim((string)($input['plan_type'] ?? ''));
$maxPc = (int)($input['max_pc_devices'] ?? 1);
$maxWeb = (int)($input['max_web_sessions'] ?? 0);
$desktopExpiry = trim((string)($input['desktop_expiry_date'] ?? ''));
$syncExpiry = trim((string)($input['sync_expiry_date'] ?? ''));

if ($customerId <= 0 || $planType === '') {
    golder_json_error(400, 'INVALID_REQUEST', 'customer_id and plan_type are required.');
}

$customer = golder_customer_by_id($master, $customerId);
if (!$customer) {
    golder_json_error(404, 'NOT_FOUND', 'Customer not found.');
}

$normalized = golder_normalize_plan_limits($planType, $maxPc, $maxWeb);
$validatedDates = golder_validate_plan_expiry_dates(
    $normalized['plan_type'],
    $desktopExpiry,
    $syncExpiry
);

if (!empty($validatedDates['errors'])) {
    golder_json_error(400, 'INVALID_PLAN_DATES', (string)reset($validatedDates['errors']));
}

$st = $master->prepare(
    'UPDATE customers
     SET plan_type = :p,
         max_pc_devices = :pc,
         max_web_sessions = :web,
         max_devices = :md,
         desktop_expiry_date = :dex,
         sync_expiry_date = :sex,
         expiry_date = :ex,
         license_status = :ls,
         license_key_id = COALESCE(license_key_id, :kid)
     WHERE id = :id'
);
$st->execute([
    ':p' => $normalized['plan_type'],
    ':pc' => $normalized['max_pc_devices'],
    ':web' => $normalized['max_web_sessions'],
    ':md' => $normalized['max_pc_devices'],
    ':dex' => (($validatedDates['desktop_expiry_date'] ?? '') !== '' ? $validatedDates['desktop_expiry_date'] : null),
    ':sex' => (($validatedDates['sync_expiry_date'] ?? '') !== '' ? $validatedDates['sync_expiry_date'] : null),
    ':ex' => (($validatedDates['expiry_date'] ?? '') !== '' ? $validatedDates['expiry_date'] : null),
    ':ls' => 'active',
    ':kid' => golder_license_key_id(),
    ':id' => $customerId,
]);

$newCustomer = golder_enforce_customer_plan($master, $customerId);
$effective = is_array($newCustomer) ? golder_customer_effective_plan($newCustomer) : golder_customer_effective_plan($customer);
$license = golder_issue_customer_license($master, $newCustomer ?: $customer);

golder_json_response([
    'status' => 'ok',
    'customer' => $newCustomer,
    'effective_plan' => $effective,
    'license' => $license,
]);
