<?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");

if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") {
    exit(0);
}

require_once "../config/database.php";

try {
    $pdo = getDBConnection();
    
    // Add missing consultation types
    $consultationTypes = [
        [
            'type_name' => 'Tatkal Booking',
            'type_code' => 'tatkal_booking',
            'base_price' => 1500.00,
            'description' => 'Emergency/urgent consultation booking',
            'is_active' => true
        ],
        [
            'type_name' => 'Video Call',
            'type_code' => 'video_call',
            'base_price' => 500.00,
            'description' => 'Online video consultation via video call',
            'is_active' => true
        ],
        [
            'type_name' => 'Audio Call',
            'type_code' => 'audio_call',
            'base_price' => 400.00,
            'description' => 'Online audio consultation via phone call',
            'is_active' => true
        ]
    ];
    
    $added = [];
    $updated = [];
    
    foreach ($consultationTypes as $type) {
        // Check if exists
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM consultation_types WHERE type_code = ?");
        $stmt->execute([$type['type_code']]);
        $exists = $stmt->fetchColumn() > 0;
        
        if ($exists) {
            // Update existing - but preserve the current is_active status
            // Do not force is_active to true as this was causing consultation types to auto-enable
            $stmt = $pdo->prepare("
                UPDATE consultation_types 
                SET type_name = ?, base_price = ?, description = ?
                WHERE type_code = ?
            ");
            $stmt->execute([
                $type['type_name'],
                $type['base_price'],
                $type['description'],
                $type['type_code']
            ]);
            $updated[] = $type['type_name'];
        } else {
            // Insert new
            $stmt = $pdo->prepare("
                INSERT INTO consultation_types (type_name, type_code, base_price, description, is_active) 
                VALUES (?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $type['type_name'],
                $type['type_code'],
                $type['base_price'],
                $type['description'],
                $type['is_active']
            ]);
            $added[] = $type['type_name'];
        }
    }
    
    echo json_encode([
        "success" => true,
        "message" => "Consultation types processed successfully",
        "added" => $added,
        "updated" => $updated
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        "success" => false,
        "message" => "Error: " . $e->getMessage()
    ]);
}
?>
