<?php
/**
 * ADMIN AJAX: Update Settings
 */
header('Content-Type: application/json; charset=utf-8');

try {
    // Initialize
    define('BASE_PATH', dirname(dirname(dirname(__DIR__))));
    require_once BASE_PATH . '/app/config/config.php';
    
    // Start session
    if (session_status() === PHP_SESSION_NONE) {
        session_name(SESSION_NAME);
        session_start();
    }
    
    // Must be POST
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        echo json_encode(['success' => false, 'message' => 'Invalid request']);
        exit;
    }
    
    // Must be admin
    if (!isAdminLoggedIn()) {
        echo json_encode(['success' => false, 'message' => 'অ্যাডমিন লগইন প্রয়োজন']);
        exit;
    }
    
    // Create settings table if not exists
    Database::getInstance()->exec("
        CREATE TABLE IF NOT EXISTS site_settings (
            id INT UNSIGNED NOT NULL AUTO_INCREMENT,
            setting_key VARCHAR(100) NOT NULL,
            setting_value TEXT,
            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            UNIQUE KEY (setting_key)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");
    
    // Settings to save
    $settingsToSave = [
        'site_name' => trim($_POST['site_name'] ?? ''),
        'site_email' => trim($_POST['site_email'] ?? ''),
        'site_phone' => trim($_POST['site_phone'] ?? ''),
        'site_address' => trim($_POST['site_address'] ?? ''),
        'bkash_number' => trim($_POST['bkash_number'] ?? ''),
        'nagad_number' => trim($_POST['nagad_number'] ?? ''),
        'whatsapp_number' => trim($_POST['whatsapp_number'] ?? ''),
        'vat_percent' => (int)($_POST['vat_percent'] ?? 15),
        'shipping_dhaka' => (int)($_POST['shipping_dhaka'] ?? SHIPPING_COST_DHAKA),
        'shipping_outside' => (int)($_POST['shipping_outside'] ?? SHIPPING_COST_OUTSIDE),
        'facebook_url' => trim($_POST['facebook_url'] ?? ''),
        'instagram_url' => trim($_POST['instagram_url'] ?? ''),
        'youtube_url' => trim($_POST['youtube_url'] ?? ''),
        'footer_about' => trim($_POST['footer_about'] ?? ''),
        'business_hours' => trim($_POST['business_hours'] ?? ''),
        'copyright_text' => trim($_POST['copyright_text'] ?? ''),
    ];
    
    // Validate required fields
    if (empty($settingsToSave['site_name'])) {
        echo json_encode(['success' => false, 'message' => 'Shop name is required']);
        exit;
    }
    
    // Save each setting
    $stmt = Database::getInstance()->prepare(
        "INSERT INTO site_settings (setting_key, setting_value) VALUES (?, ?)
         ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)"
    );
    
    foreach ($settingsToSave as $key => $value) {
        $stmt->execute([$key, $value]);
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'সেটিংস সফলভাবে সংরক্ষিত হয়েছে!'
    ]);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
