<?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();
    
    // Create consultation_types table if it doesn't exist
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS consultation_types (
            id INT AUTO_INCREMENT PRIMARY KEY,
            type_name VARCHAR(100) NOT NULL,
            type_code VARCHAR(50) UNIQUE NOT NULL,
            base_price DECIMAL(10,2) NOT NULL DEFAULT 0.00,
            description TEXT,
            is_active BOOLEAN DEFAULT TRUE,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_type_code (type_code),
            INDEX idx_is_active (is_active)
        )
    ");
    
    // Check if table has data, if not insert defaults
    $stmt = $pdo->query("SELECT COUNT(*) as count FROM consultation_types");
    $count = $stmt->fetch()['count'];
    
    if ($count == 0) {
        $pdo->exec("
            INSERT INTO consultation_types (type_name, type_code, base_price, description, is_active) VALUES
            ('Video Call', 'video_call', 500.00, 'Online video consultation via video call', TRUE),
            ('Audio Call', 'audio_call', 400.00, 'Online audio consultation via phone call', TRUE),
            ('Office Meeting', 'office_meeting', 600.00, 'In-person consultation at office', TRUE),
            ('Tatkal Booking', 'tatkal_booking', 1500.00, 'Emergency/urgent consultation booking', TRUE)
        ");
    }
    
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        // Get all consultation types
        $stmt = $pdo->prepare("
            SELECT 
                id,
                type_name,
                type_code,
                base_price,
                description,
                is_active,
                created_at
            FROM consultation_types 
            ORDER BY id ASC
        ");
        $stmt->execute();
        $consultationTypes = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode([
            'success' => true,
            'consultation_types' => $consultationTypes,
            'total_types' => count($consultationTypes)
        ]);
        
    } elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $raw_input = file_get_contents('php://input');
    $input = json_decode($raw_input, true);
    
    // Debug logging
    error_log("Consultation Types API - Raw Input: " . $raw_input);
    error_log("Consultation Types API - Decoded Input: " . print_r($input, true));
    
    if (!$input) {
        throw new Exception('Invalid JSON input. Raw input: ' . $raw_input);
    }
    
    $action = $input['action'] ?? '';
        
        switch ($action) {
            case 'create':
                createConsultationType($pdo, $input);
                break;
            case 'update':
                updateConsultationType($pdo, $input);
                break;
            case 'delete':
                deleteConsultationType($pdo, $input);
                break;
            default:
                throw new Exception('Invalid action');
        }
    } else {
        throw new Exception('Method not allowed');
    }
    
} catch (Exception $e) {
    http_response_code(400);
    error_log("Consultation Types API Error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage(),
        'debug_info' => [
            'raw_input' => $raw_input ?? 'N/A',
            'parsed_input' => $input ?? 'N/A',
            'action' => $action ?? 'N/A'
        ]
    ]);
} catch (PDOException $e) {
    http_response_code(500);
    error_log("Consultation Types API Database Error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Database error occurred: ' . $e->getMessage()
    ]);
}

function createConsultationType($pdo, $input) {
    // Validate required fields
    $required_fields = ['type_name', 'type_code', 'base_price'];
    foreach ($required_fields as $field) {
        if (empty($input[$field])) {
            throw new Exception("Field '$field' is required");
        }
    }
    
    // Check if type_code already exists
    $stmt = $pdo->prepare("SELECT id FROM consultation_types WHERE type_code = ?");
    $stmt->execute([$input['type_code']]);
    if ($stmt->fetch()) {
        throw new Exception('Type code already exists');
    }
    
    // Insert new consultation type
    $stmt = $pdo->prepare("
        INSERT INTO consultation_types (
            type_name, 
            type_code, 
            base_price, 
            description, 
            is_active
        ) VALUES (?, ?, ?, ?, ?)
    ");
    
    $stmt->execute([
        $input['type_name'],
        $input['type_code'],
        $input['base_price'],
        $input['description'] ?? '',
        $input['is_active'] ?? 1
    ]);
    
    echo json_encode([
        'success' => true,
        'message' => 'Consultation type created successfully',
        'id' => $pdo->lastInsertId()
    ]);
}

function updateConsultationType($pdo, $input) {
    // Validate required fields
    if (empty($input['id'])) {
        throw new Exception('ID is required for update');
    }
    
    $required_fields = ['type_name', 'type_code', 'base_price'];
    foreach ($required_fields as $field) {
        if (empty($input[$field])) {
            throw new Exception("Field '$field' is required");
        }
    }
    
    // Check if type_code already exists (excluding current record)
    $stmt = $pdo->prepare("SELECT id FROM consultation_types WHERE type_code = ? AND id != ?");
    $stmt->execute([$input['type_code'], $input['id']]);
    if ($stmt->fetch()) {
        throw new Exception('Type code already exists');
    }
    
    // Update consultation type
    $stmt = $pdo->prepare("
        UPDATE consultation_types SET 
            type_name = ?, 
            type_code = ?, 
            base_price = ?, 
            description = ?, 
            is_active = ?
        WHERE id = ?
    ");
    
    $stmt->execute([
        $input['type_name'],
        $input['type_code'],
        $input['base_price'],
        $input['description'] ?? '',
        $input['is_active'] ?? 1,
        $input['id']
    ]);
    
    if ($stmt->rowCount() === 0) {
        throw new Exception('Consultation type not found');
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Consultation type updated successfully'
    ]);
}

function deleteConsultationType($pdo, $input) {
    if (empty($input['id'])) {
        throw new Exception('ID is required for delete');
    }
    
    // Check if consultation type is being used in appointments
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM appointments WHERE consultation_type = (SELECT type_code FROM consultation_types WHERE id = ?)");
    $stmt->execute([$input['id']]);
    $appointmentCount = $stmt->fetchColumn();
    
    if ($appointmentCount > 0) {
        throw new Exception('Cannot delete consultation type that is being used in appointments');
    }
    
    // Delete consultation type
    $stmt = $pdo->prepare("DELETE FROM consultation_types WHERE id = ?");
    $stmt->execute([$input['id']]);
    
    if ($stmt->rowCount() === 0) {
        throw new Exception('Consultation type not found');
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Consultation type deleted successfully'
    ]);
}
?>
