<?php
/**
 * Email Management API for Web Hosting Panel
 * Handles AJAX requests for email account operations
 */

// Set content type to JSON
header('Content-Type: application/json');

// Check authentication
if (!defined('AUTH_USER')) {
    http_response_code(401);
    echo json_encode(['status' => 'error', 'message' => 'Authentication required']);
    exit();
}

require_once('/docker/whp/web/libs/emailmgmt.php');

$EmailMgmt = new emailmgmt();

// Get request method and action
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

// For POST requests, also check for action in JSON body
if ($method === 'POST' && empty($action)) {
    $input = json_decode(file_get_contents('php://input'), true);
    if ($input && !empty($input['action'])) {
        $action = $input['action'];
        
        // If CSRF token is in JSON body, make it available for validation
        if (isset($input['csrf_token']) && !isset($_POST['csrf_token'])) {
            $_POST['csrf_token'] = $input['csrf_token'];
        }
    }
}

// Handle different actions
switch ($action) {
    case 'get_accounts':
        if ($method === 'GET') {
            $result = $EmailMgmt->getEmailAccounts(AUTH_USER);
            echo json_encode($result);
        } else {
            http_response_code(405);
            echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
        }
        break;
        
    case 'get_domains':
        if ($method === 'GET') {
            $result = $EmailMgmt->getUserDomains(AUTH_USER);
            echo json_encode($result);
        } else {
            http_response_code(405);
            echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
        }
        break;
        
    case 'get_user_domains':
        if ($method === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            
            if (!$input) {
                $input = $_POST;
            }
            
            // Only root users can get domains for other users
            if (AUTH_USER !== 'root') {
                echo json_encode(['status' => 'error', 'message' => 'Permission denied']);
                break;
            }
            
            if (empty($input['username'])) {
                echo json_encode(['status' => 'error', 'message' => 'Username required']);
                break;
            }
            
            $result = $EmailMgmt->getUserDomains($input['username']);
            echo json_encode($result);
        } else {
            http_response_code(405);
            echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
        }
        break;
        
    case 'get_usage_stats':
        if ($method === 'GET') {
            $result = $EmailMgmt->getEmailUsageStats(AUTH_USER);
            echo json_encode($result);
        } else {
            http_response_code(405);
            echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
        }
        break;
        
    case 'create_account':
        if ($method === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            
            if (!$input) {
                $input = $_POST;
            }
            
            if (empty($input['email_address']) || empty($input['password']) || empty($input['domain_name'])) {
                echo json_encode(['status' => 'error', 'message' => 'Missing required fields']);
                break;
            }
            
            $result = $EmailMgmt->createEmailAccount(
                AUTH_USER,
                $input['email_address'],
                $input['password'],
                $input['domain_name'],
                $input['quota_mb'] ?? 100
            );
            
            echo json_encode($result);
        } else {
            http_response_code(405);
            echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
        }
        break;
        
    case 'update_account':
        if ($method === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            
            if (!$input) {
                $input = $_POST;
            }
            
            if (empty($input['email_id'])) {
                echo json_encode(['status' => 'error', 'message' => 'Email ID required']);
                break;
            }
            
            $result = $EmailMgmt->updateEmailAccount(
                intval($input['email_id']),
                AUTH_USER,
                $input['password'] ?? null,
                $input['quota_mb'] ?? null,
                $input['active'] ?? null
            );
            
            echo json_encode($result);
        } else {
            http_response_code(405);
            echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
        }
        break;
        
    case 'delete_account':
        if ($method === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            
            if (!$input) {
                $input = $_POST;
            }
            
            if (empty($input['email_id'])) {
                echo json_encode(['status' => 'error', 'message' => 'Email ID required']);
                break;
            }
            
            $result = $EmailMgmt->deleteEmailAccount(intval($input['email_id']), AUTH_USER);
            echo json_encode($result);
        } else {
            http_response_code(405);
            echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
        }
        break;
        
    case 'get_forwarders':
        if ($method === 'GET') {
            $result = $EmailMgmt->getEmailForwarders(AUTH_USER);
            echo json_encode($result);
        } else {
            http_response_code(405);
            echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
        }
        break;
        
    case 'create_forwarder':
        if ($method === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            
            if (!$input) {
                $input = $_POST;
            }
            
            if (empty($input['source_email']) || empty($input['destination_email'])) {
                echo json_encode(['status' => 'error', 'message' => 'Missing required fields']);
                break;
            }
            
            $result = $EmailMgmt->createEmailForwarder(
                AUTH_USER,
                $input['source_email'],
                $input['destination_email']
            );
            
            echo json_encode($result);
        } else {
            http_response_code(405);
            echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
        }
        break;
        
    case 'delete_forwarder':
        if ($method === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            
            if (!$input) {
                $input = $_POST;
            }
            
            if (empty($input['forwarder_id'])) {
                echo json_encode(['status' => 'error', 'message' => 'Forwarder ID required']);
                break;
            }
            
            $result = $EmailMgmt->deleteEmailForwarder(intval($input['forwarder_id']), AUTH_USER);
            echo json_encode($result);
        } else {
            http_response_code(405);
            echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
        }
        break;
        
    case 'get_aliases':
        if ($method === 'GET') {
            $result = $EmailMgmt->getEmailAliases(AUTH_USER);
            echo json_encode($result);
        } else {
            http_response_code(405);
            echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
        }
        break;
        
    case 'create_alias':
        if ($method === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            
            if (!$input) {
                $input = $_POST;
            }
            
            if (empty($input['alias_email']) || empty($input['target_email'])) {
                echo json_encode(['status' => 'error', 'message' => 'Missing required fields']);
                break;
            }
            
            $result = $EmailMgmt->createEmailAlias(
                AUTH_USER,
                $input['alias_email'],
                $input['target_email']
            );
            
            echo json_encode($result);
        } else {
            http_response_code(405);
            echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
        }
        break;
        
    case 'delete_alias':
        if ($method === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            
            if (!$input) {
                $input = $_POST;
            }
            
            if (empty($input['alias_id'])) {
                echo json_encode(['status' => 'error', 'message' => 'Alias ID required']);
                break;
            }
            
            $result = $EmailMgmt->deleteEmailAlias(intval($input['alias_id']), AUTH_USER);
            echo json_encode($result);
        } else {
            http_response_code(405);
            echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
        }
        break;
        
    case 'check_limits':
        if ($method === 'GET') {
            $result = $EmailMgmt->canCreateEmailAccount(AUTH_USER);
            echo json_encode($result);
        } else {
            http_response_code(405);
            echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
        }
        break;
        
    case 'get_email_stats':
        if ($method === 'GET') {
            $email_address = $_GET['email'] ?? '';
            if (empty($email_address)) {
                echo json_encode(['status' => 'error', 'message' => 'Email address is required']);
                break;
            }
            
            $result = $EmailMgmt->getEmailStatsSummary($email_address);
            echo json_encode($result);
        } else {
            http_response_code(405);
            echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
        }
        break;
        
    case 'update_domain':
        if ($method === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            
            if (!$input) {
                $input = $_POST;
            }
            
            if (empty($input['domain_name'])) {
                echo json_encode(['status' => 'error', 'message' => 'Domain name is required']);
                break;
            }
            
            // Only root users can update domains
            if (AUTH_USER !== 'root') {
                echo json_encode(['status' => 'error', 'message' => 'Permission denied']);
                break;
            }
            
            $updates = [];
            $updateable_fields = [
                'forward', 'forward_domain', 'domain_bin', 'domain_bin_address',
                'force_route', 'force_route_host', 'custom_outbound', 'outbound_ip',
                'outbound_ehlo', 'reference_id', 'disabled', 'name'
            ];
            
            foreach ($updateable_fields as $field) {
                if (isset($input[$field])) {
                    // Convert checkbox values to proper boolean for disabled field
                    if ($field === 'disabled') {
                        $updates[$field] = ($input[$field] === '1' || $input[$field] === true);
                    } else {
                        $updates[$field] = $input[$field];
                    }
                }
            }
            
            if (empty($updates)) {
                echo json_encode(['status' => 'error', 'message' => 'No updates specified']);
                break;
            }
            
            $result = $EmailMgmt->updateMailServerDomain($input['domain_name'], $updates);
            echo json_encode($result);
        } else {
            http_response_code(405);
            echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
        }
        break;
        
    case 'get_domain':
        if ($method === 'GET') {
            $domain_name = $_GET['domain'] ?? '';
            if (empty($domain_name)) {
                echo json_encode(['status' => 'error', 'message' => 'Domain name is required']);
                break;
            }
            
            // Only root users can get domain details
            if (AUTH_USER !== 'root') {
                echo json_encode(['status' => 'error', 'message' => 'Permission denied']);
                break;
            }
            
            $result = $EmailMgmt->getMailServerDomain($domain_name);
            echo json_encode($result);
        } else {
            http_response_code(405);
            echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
        }
        break;
        
    case 'create_dkim':
        if ($method === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            
            if (!$input) {
                $input = $_POST;
            }
            
            if (empty($input['domain_name'])) {
                echo json_encode(['status' => 'error', 'message' => 'Domain name is required']);
                break;
            }
            
            // All authenticated users can create DKIM records for their own domains
            $result = $EmailMgmt->createDkimRecords($input['domain_name'], AUTH_USER);
            echo json_encode($result);
        } else {
            http_response_code(405);
            echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
        }
        break;
        
    case 'get_dkim':
        if ($method === 'GET') {
            $domain_name = $_GET['domain'] ?? '';
            if (empty($domain_name)) {
                echo json_encode(['status' => 'error', 'message' => 'Domain name is required']);
                break;
            }
            
            // All authenticated users can get DKIM records for their own domains
            $result = $EmailMgmt->getDkimRecords($domain_name, AUTH_USER);
            echo json_encode($result);
        } else {
            http_response_code(405);
            echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
        }
        break;
        
    case 'rotate_dkim':
        if ($method === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            
            if (!$input) {
                $input = $_POST;
            }
            
            if (empty($input['domain_name'])) {
                echo json_encode(['status' => 'error', 'message' => 'Domain name is required']);
                break;
            }
            
            // All authenticated users can rotate DKIM records for their own domains
            $result = $EmailMgmt->rotateDkimRecords($input['domain_name'], AUTH_USER);
            echo json_encode($result);
        } else {
            http_response_code(405);
            echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
        }
        break;
        
    case 'retry_dkim':
        if ($method === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            
            if (!$input) {
                $input = $_POST;
            }
            
            if (empty($input['domain_name'])) {
                echo json_encode(['status' => 'error', 'message' => 'Domain name is required']);
                break;
            }
            
            // All authenticated users can retry DKIM creation for their own domains
            $max_retries = isset($input['max_retries']) ? intval($input['max_retries']) : 5;
            $delay_seconds = isset($input['delay_seconds']) ? intval($input['delay_seconds']) : 3;
            
            $result = $EmailMgmt->retryDkimCreation($input['domain_name'], AUTH_USER, $max_retries, $delay_seconds);
            echo json_encode($result);
        } else {
            http_response_code(405);
            echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
        }
        break;
        
    default:
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Invalid action']);
        break;
}
?> 