<?php
/**
 * save_config.php — Admin Panel Config Writer
 * Place this file in /jioooo/ (same folder as admin.html)
 * PHP must have write permission to ../data/ directory
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

// ─── ADMIN PASSWORD (must match admin.html) ───────────
define('ADMIN_PASSWORD', 'admin@jio123');  // ← change this!

// ─── OUTPUT PATH ──────────────────────────────────────
$configDir  = __DIR__ . '/data';
$configFile = $configDir . '/info.json';

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

// Parse body
$body = file_get_contents('php://input');
$data = json_decode($body, true);

if (!$data) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Invalid JSON']);
    exit;
}

// Validate password
if (!isset($data['password']) || $data['password'] !== ADMIN_PASSWORD) {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

// Validate config fields
$config = $data['config'] ?? [];
$name   = trim($config['name'] ?? '');
$email  = trim($config['email'] ?? '');

if (empty($name) || empty($email)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Both UPI IDs are required']);
    exit;
}

// Basic UPI ID format check (contains @ sign)
if (strpos($name, '@') === false || strpos($email, '@') === false) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Invalid UPI ID format (must contain @)']);
    exit;
}

// Create data dir if missing
if (!is_dir($configDir)) {
    if (!mkdir($configDir, 0755, true)) {
        http_response_code(500);
        echo json_encode(['success' => false, 'error' => 'Failed to create data directory']);
        exit;
    }
}

// Write file
$payload = json_encode(['name' => $name, 'email' => $email], JSON_PRETTY_PRINT);
$result  = file_put_contents($configFile, $payload, LOCK_EX);

if ($result === false) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Failed to write config file. Check folder permissions.']);
    exit;
}

echo json_encode([
    'success'  => true,
    'message'  => 'Config saved successfully',
    'saved_at' => date('Y-m-d H:i:s'),
    'path'     => $configFile
]);
