<?php
// =============================================================================
// /api/vpns_bulk_zip.php — accept a ZIP of .ovpn server files, create one
// vpn_profiles row per file. Credentials are set separately in the
// Credentials tab.
//
// POST multipart/form-data: file (.zip), provider (default 'Other')
// Returns: { ok, created: N, skipped: N, errors: [...] }
// =============================================================================
require_once __DIR__ . '/_common.php';
require_csrf_unless_get();

require_method('POST');

if (empty($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
    json_error('zip upload required', 400);
}
if (!class_exists('ZipArchive')) json_error('ZipArchive extension required', 500);

$provider = (string)($_POST['provider'] ?? 'Other');

$zip = new ZipArchive();
if ($zip->open($_FILES['file']['tmp_name']) !== true) json_error('invalid zip', 400);

$created = 0; $skipped = 0; $errors = [];
$now = time();
for ($i = 0; $i < $zip->numFiles; $i++) {
    $stat = $zip->statIndex($i);
    $name = $stat['name'] ?? '';
    if ($name === '' || substr($name, -1) === '/') continue;
    $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
    if ($ext !== 'ovpn') { $skipped++; continue; }
    if ((int)$stat['size'] > 256 * 1024) { $errors[] = "$name too large"; continue; }

    $ovpn = $zip->getFromIndex($i);
    if ($ovpn === false) { $errors[] = "$name unreadable"; continue; }

    // Derive a friendly name + country/state from the filename when possible.
    // Conventions seen in PIA / Mullvad / NordVPN exports:
    //   "US Atlanta.ovpn" / "us-atlanta.ovpn" / "nl_amsterdam.ovpn"
    $base = preg_replace('/\.ovpn$/i', '', basename($name));
    $clean = preg_replace('/[_\-]+/', ' ', $base);
    $parts = preg_split('/\s+/', trim($clean));
    $country = $parts[0] ?? '';
    $state   = trim(implode(' ', array_slice($parts, 1)));

    db_insert(
        'INSERT INTO vpn_profiles (name, provider, country, state, url, ovpn, username, password, sort_order, enabled)
         VALUES (?, ?, ?, ?, ?, ?, "", "", 0, 1)',
        [$base, $provider, $country, $state, '', $ovpn]
    );
    $created++;
}
$zip->close();

json_response(['ok' => true, 'created' => $created, 'skipped' => $skipped, 'errors' => $errors]);
