<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// Handle preflight request
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit();
}

require_once '../config/database.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        $pdo = getDBConnection();
        
        // Get JSON input
        $input = json_decode(file_get_contents('php://input'), true);
        
        if (!$input) {
            echo json_encode(['success' => false, 'message' => 'Invalid JSON input']);
            exit();
        }
        
        // Validate required fields
        $tatkalEnabled = $input['tatkal_enabled'] ?? '0';
        $tatkalPrice = $input['tatkal_price'] ?? '1500';
        $tatkalSlots = $input['tatkal_slots'] ?? '10';
        $tatkalDays = $input['tatkal_days'] ?? [];
        
        // Prepare statement for updating settings
        $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
        
        // Update tatkal enabled status
        $stmt->execute(['tatkal_enabled', $tatkalEnabled, $tatkalEnabled]);
        
        // Update tatkal price
        $stmt->execute(['tatkal_price', $tatkalPrice, $tatkalPrice]);
        
        // Update tatkal slots
        $stmt->execute(['tatkal_slots', $tatkalSlots, $tatkalSlots]);
        
        // Update individual day settings
        $allDays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
        foreach ($allDays as $day) {
            $dayEnabled = in_array($day, $tatkalDays) ? '1' : '0';
            $dayKey = 'tatkal_' . $day . '_enabled';
            $stmt->execute([$dayKey, $dayEnabled, $dayEnabled]);
        }
        
        // Also update consultation_types table if tatkal_booking exists
        if ($tatkalEnabled === '1') {
            $consultationStmt = $pdo->prepare("UPDATE consultation_types SET base_price = ?, is_active = 1 WHERE type_code = 'tatkal_booking'");
            $consultationStmt->execute([$tatkalPrice]);
            
            // If no rows affected, insert new record
            if ($consultationStmt->rowCount() === 0) {
                $insertStmt = $pdo->prepare("INSERT INTO consultation_types (type_name, type_code, base_price, description, is_active) VALUES (?, ?, ?, ?, ?)");
                $insertStmt->execute(['Tatkal Booking', 'tatkal_booking', $tatkalPrice, 'Emergency/urgent consultation booking', 1]);
            }
        } else {
            // Disable tatkal in consultation_types
            $consultationStmt = $pdo->prepare("UPDATE consultation_types SET is_active = 0 WHERE type_code = 'tatkal_booking'");
            $consultationStmt->execute();
        }
        
        echo json_encode([
            'success' => true,
            'message' => 'Tatkal settings updated successfully',
            'settings' => [
                'tatkal_enabled' => $tatkalEnabled,
                'tatkal_price' => $tatkalPrice,
                'tatkal_slots' => $tatkalSlots,
                'tatkal_days' => $tatkalDays
            ]
        ]);
        
    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'message' => 'Error updating tatkal settings: ' . $e->getMessage()
        ]);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
}
?>