<?php
/**
 * API Handler for Form Submissions
 * SSCI Office Platform
 */

$auth = $GLOBALS['auth'];
$db = $GLOBALS['db'];

// Check if this is a REST API endpoint call
$endpoint = $_GET['endpoint'] ?? null;
if ($endpoint) {
    // Route to REST API handlers
    require SSCI_ROOT . '/public/api.php';
    exit();
}

switch ($action) {
    // Profile API
    case 'saveProfile':
        handleSaveProfile();
        break;
    case 'changePassword':
        handleChangePassword();
        break;
    case 'savePreferences':
        handleSavePreferences();
        break;

    // Settings API - Unified Handler
    case 'saveSettings':
        handleSaveSettings();
        break;

    // Legacy individual handlers (kept for backward compatibility)
    case 'saveGeneralSettings':
        handleSaveGeneralSettings();
        break;
    case 'saveAppearanceSettings':
        handleSaveAppearanceSettings();
        break;
    case 'saveEmailSettings':
        handleSaveEmailSettings();
        break;
    case 'saveNotificationSettings':
        handleSaveNotificationSettings();
        break;
    case 'saveAppSettings':
        handleSaveAppSettings();
        break;
    case 'saveDatabaseSettings':
        handleSaveDatabaseSettings();
        break;
    case 'savePaymentGatewaySettings':
        handleSavePaymentGatewaySettings();
        break;

    default:
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
        exit();
}

// Profile Handlers
function handleSaveProfile() {
    global $db, $auth;
    
    try {
        $user = $auth->getCurrentUser();
        $userId = $user['id'];
        
        $name = $_POST['name'] ?? '';
        $phone = $_POST['phone'] ?? '';
        $whatsapp = $_POST['whatsapp'] ?? '';
        $address = $_POST['address'] ?? '';
        $photo = $_POST['photo_data'] ?? null;
        
        // Validate
        if (empty($name)) {
            echo json_encode(['success' => false, 'message' => 'Name is required']);
            exit();
        }
        
        // Handle photo if provided
        $photoPath = null;
        if (!empty($photo) && strpos($photo, 'data:image') === 0) {
            // Decode base64 photo
            $photoData = substr($photo, strpos($photo, ',') + 1);
            $photoData = base64_decode($photoData);
            
            // Create uploads directory if it doesn't exist
            $uploadsDir = __DIR__ . '/../public/uploads/profiles/';
            if (!is_dir($uploadsDir)) {
                mkdir($uploadsDir, 0755, true);
            }
            
            // Save photo with unique filename
            $filename = 'user_' . $userId . '_' . time() . '.jpg';
            $filepath = $uploadsDir . $filename;
            
            if (file_put_contents($filepath, $photoData) !== false) {
                $photoPath = '/public/uploads/profiles/' . $filename;
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to upload photo']);
                exit();
            }
        }
        
        // Build UPDATE query
        $sql = 'UPDATE users SET name = ?, phone = ?, whatsapp = ?, address = ?';
        $params = [$name, $phone, $whatsapp, $address];
        
        if ($photoPath) {
            $sql .= ', photo = ?';
            $params[] = $photoPath;
        }
        
        $sql .= ' WHERE id = ?';
        $params[] = $userId;
        
        // Execute update
        $db->query($sql, $params);
        
        echo json_encode(['success' => true, 'message' => 'Profile updated successfully']);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Error saving profile: ' . $e->getMessage()]);
    }
}

function handleChangePassword() {
    global $db, $auth;
    
    try {
        $user = $auth->getCurrentUser();
        $userId = $user['id'];
        
        $currentPassword = $_POST['current_password'] ?? '';
        $newPassword = $_POST['new_password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';
        
        // Validate
        if (empty($currentPassword) || empty($newPassword) || empty($confirmPassword)) {
            echo json_encode(['success' => false, 'message' => 'All fields are required']);
            exit();
        }
        
        if ($newPassword !== $confirmPassword) {
            echo json_encode(['success' => false, 'message' => 'Passwords do not match']);
            exit();
        }
        
        if (strlen($newPassword) < 8) {
            echo json_encode(['success' => false, 'message' => 'Password must be at least 8 characters']);
            exit();
        }
        
        // Verify current password
        if (!password_verify($currentPassword, $user['password'])) {
            echo json_encode(['success' => false, 'message' => 'Current password is incorrect']);
            exit();
        }
        
        // Update password
        $hashedPassword = password_hash($newPassword, PASSWORD_BCRYPT);
        $db->query('UPDATE users SET password = ? WHERE id = ?', [$hashedPassword, $userId]);
        
        echo json_encode(['success' => true, 'message' => 'Password changed successfully']);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Error changing password: ' . $e->getMessage()]);
    }
}

function handleSavePreferences() {
    global $db, $auth;
    
    try {
        $user = $auth->getCurrentUser();
        $userId = $user['id'];
        
        $language = $_POST['language'] ?? 'en';
        $emailNotifications = isset($_POST['email_notifications']) ? 1 : 0;
        $inAppNotifications = isset($_POST['in_app_notifications']) ? 1 : 0;
        $smsNotifications = isset($_POST['sms_notifications']) ? 1 : 0;
        
        $db->query(
            'UPDATE users SET language = ?, email_notifications = ?, in_app_notifications = ?, sms_notifications = ? WHERE id = ?',
            [$language, $emailNotifications, $inAppNotifications, $smsNotifications, $userId]
        );
        // Update session language
        if (isset($_SESSION)) {
            $_SESSION['language'] = $language;
        }
        echo json_encode(['success' => true, 'message' => 'Preferences updated successfully']);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Error saving preferences: ' . $e->getMessage()]);
    }
}

// Unified Settings Handler
function handleSaveSettings() {
    global $db;
    
    try {
        // Collect all settings data
        $updates = [];
        $params = [];
        
        // General Settings
        if (isset($_POST['site_name'])) {
            $updates[] = 'site_name = ?';
            $params[] = $_POST['site_name'];
        }
        if (isset($_POST['site_acronym'])) {
            $updates[] = 'site_acronym = ?';
            $params[] = $_POST['site_acronym'];
        }
        if (isset($_POST['email'])) {
            $updates[] = 'email = ?';
            $params[] = $_POST['email'];
        }
        if (isset($_POST['phone'])) {
            $updates[] = 'phone = ?';
            $params[] = $_POST['phone'];
        }
        if (isset($_POST['address'])) {
            $updates[] = 'address = ?';
            $params[] = $_POST['address'];
        }
        
        // Appearance Settings
        if (isset($_POST['primary_color'])) {
            $updates[] = 'primary_color = ?';
            $params[] = $_POST['primary_color'];
        }
        
        // Handle file uploads
        if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
            $logo = handleFileUpload($_FILES['logo'], 'logo');
            if ($logo) {
                $updates[] = 'site_logo = ?';
                $params[] = $logo;
            }
        }
        
        if (isset($_FILES['letterhead']) && $_FILES['letterhead']['error'] === UPLOAD_ERR_OK) {
            $letterhead = handleFileUpload($_FILES['letterhead'], 'letterhead');
            if ($letterhead) {
                $updates[] = 'site_letterhead = ?';
                $params[] = $letterhead;
            }
        }
        
        // Email Settings
        if (isset($_POST['email_enabled'])) {
            $updates[] = 'email_enabled = ?';
            $params[] = 1;
        } else {
            $updates[] = 'email_enabled = ?';
            $params[] = 0;
        }
        
        if (isset($_POST['smtp_host'])) {
            $updates[] = 'smtp_host = ?';
            $params[] = $_POST['smtp_host'];
        }
        if (isset($_POST['smtp_port'])) {
            $updates[] = 'smtp_port = ?';
            $params[] = $_POST['smtp_port'];
        }
        if (isset($_POST['smtp_user'])) {
            $updates[] = 'smtp_user = ?';
            $params[] = $_POST['smtp_user'];
        }
        if (isset($_POST['smtp_password']) && !empty($_POST['smtp_password'])) {
            $updates[] = 'smtp_password = ?';
            $params[] = $_POST['smtp_password'];
        }
        if (isset($_POST['smtp_from'])) {
            $updates[] = 'smtp_from = ?';
            $params[] = $_POST['smtp_from'];
        }
        
        // Notification Settings
        if (isset($_POST['sms_enabled'])) {
            $updates[] = 'sms_enabled = ?';
            $params[] = 1;
        } else {
            $updates[] = 'sms_enabled = ?';
            $params[] = 0;
        }
        
        if (isset($_POST['sms_gateway_token'])) {
            $updates[] = 'sms_gateway_token = ?';
            $params[] = $_POST['sms_gateway_token'];
        }
        if (isset($_POST['whatsapp_api_token'])) {
            $updates[] = 'whatsapp_api_token = ?';
            $params[] = $_POST['whatsapp_api_token'];
        }
        if (isset($_POST['push_enabled'])) {
            $updates[] = 'push_enabled = ?';
            $params[] = 1;
        } else {
            $updates[] = 'push_enabled = ?';
            $params[] = 0;
        }
        
        // Build and execute UPDATE query
        if (!empty($updates)) {
            $sql = 'UPDATE settings SET ' . implode(', ', $updates) . ' LIMIT 1';
            $db->query($sql, $params);
        }
        
        echo json_encode(['success' => true, 'message' => 'Settings updated successfully']);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Error saving settings: ' . $e->getMessage()]);
    }
}

// Settings Handlers
function handleSaveGeneralSettings() {
    global $db;
    
    try {
        $siteName = $_POST['site_name'] ?? '';
        $siteAcronym = $_POST['site_acronym'] ?? '';
        $email = $_POST['email'] ?? '';
        $phone = $_POST['phone'] ?? '';
        $address = $_POST['address'] ?? '';
        
        // Update database settings table
        $db->query(
            'UPDATE settings SET site_name = ?, site_acronym = ?, email = ?, phone = ?, address = ? LIMIT 1',
            [$siteName, $siteAcronym, $email, $phone, $address]
        );
        
        // Update .env file if possible
        updateEnvFile([
            'APP_NAME' => $siteName,
            'APP_ACRONYM' => $siteAcronym,
            'APP_EMAIL' => $email,
            'APP_PHONE' => $phone
        ]);
        
        echo json_encode(['success' => true, 'message' => 'General settings updated successfully']);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Error saving settings: ' . $e->getMessage()]);
    }
}

function handleSaveAppearanceSettings() {
    global $db;
    
    try {
        $primaryColor = $_POST['primary_color'] ?? '#2563eb';
        
        // Handle file uploads for logo and letterhead
        $logo = null;
        $letterhead = null;
        
        if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
            $logo = handleFileUpload($_FILES['logo'], 'logo');
        }
        
        if (isset($_FILES['letterhead']) && $_FILES['letterhead']['error'] === UPLOAD_ERR_OK) {
            $letterhead = handleFileUpload($_FILES['letterhead'], 'letterhead');
        }
        
        $updateData = ['primary_color' => $primaryColor];
        
        if ($logo) {
            $updateData['logo'] = $logo;
        }
        if ($letterhead) {
            $updateData['letterhead'] = $letterhead;
        }
        
        // Build SQL and params
        $sql = 'UPDATE settings SET primary_color = ?';
        $params = [$primaryColor];
        if ($logo) {
            $sql .= ', logo = ?';
            $params[] = $logo;
        }
        if ($letterhead) {
            $sql .= ', letterhead = ?';
            $params[] = $letterhead;
        }
        $sql .= ' LIMIT 1';
        $db->query($sql, $params);
        
        // Update .env file if possible
        updateEnvFile([
            'PRIMARY_COLOR' => $primaryColor
        ]);
        
        echo json_encode(['success' => true, 'message' => 'Appearance settings updated successfully']);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Error saving appearance settings: ' . $e->getMessage()]);
    }
}

function handleSaveEmailSettings() {
    global $db;
    
    try {
        $emailEnabled = isset($_POST['email_enabled']) ? 1 : 0;
        $smtpHost = $_POST['smtp_host'] ?? '';
        $smtpPort = $_POST['smtp_port'] ?? '587';
        $smtpUser = $_POST['smtp_user'] ?? '';
        $smtpPassword = $_POST['smtp_password'] ?? '';
        $smtpFrom = $_POST['smtp_from'] ?? '';
        
        // Update database settings
        $db->query(
            'UPDATE settings SET email_enabled = ?, smtp_host = ?, smtp_port = ?, smtp_user = ?, smtp_password = ?, smtp_from = ? LIMIT 1',
            [$emailEnabled, $smtpHost, $smtpPort, $smtpUser, $smtpPassword, $smtpFrom]
        );
        
        // Update .env file if possible
        updateEnvFile([
            'EMAIL_ENABLED' => $emailEnabled ? 'true' : 'false',
            'SMTP_HOST' => $smtpHost,
            'SMTP_PORT' => $smtpPort,
            'SMTP_USER' => $smtpUser,
            'SMTP_PASSWORD' => $smtpPassword,
            'SMTP_FROM' => $smtpFrom
        ]);
        
        echo json_encode(['success' => true, 'message' => 'Email settings updated successfully']);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Error saving email settings: ' . $e->getMessage()]);
    }
}

function handleSaveNotificationSettings() {
    global $db;
    
    try {
        // SMS Settings
        $smsNotificationsEnabled = isset($_POST['sms_notifications_enabled']) ? 1 : 0;
        $smsUsername = $_POST['sms_username'] ?? '';
        $smsPassword = $_POST['sms_password'] ?? '';
        
        // WhatsApp Settings
        $whatsappNotificationsEnabled = isset($_POST['whatsapp_notifications_enabled']) ? 1 : 0;
        $whatsappInstanceId = $_POST['whatsapp_instance_id'] ?? '';
        $whatsappApiToken = $_POST['whatsapp_api_token'] ?? '';
        
        // Push Notifications
        $pushNotificationsEnabled = isset($_POST['push_notifications_enabled']) ? 1 : 0;
        $vapidPublicKey = $_POST['vapid_public_key'] ?? '';
        $vapidPrivateKey = $_POST['vapid_private_key'] ?? '';
        
        // Update database settings
        $db->query(
            'UPDATE settings SET 
                sms_notifications_enabled = ?, 
                sms_username = ?, 
                sms_password = ?, 
                whatsapp_notifications_enabled = ?, 
                whatsapp_instance_id = ?, 
                whatsapp_api_token = ?, 
                push_notifications_enabled = ?, 
                vapid_public_key = ?, 
                vapid_private_key = ? 
             LIMIT 1',
            [
                $smsNotificationsEnabled, $smsUsername, $smsPassword,
                $whatsappNotificationsEnabled, $whatsappInstanceId, $whatsappApiToken,
                $pushNotificationsEnabled, $vapidPublicKey, $vapidPrivateKey
            ]
        );
        
        // Update .env file if possible
        updateEnvFile([
            'SMS_ENABLED' => $smsNotificationsEnabled ? 'true' : 'false',
            'SMS_USERNAME' => $smsUsername,
            'SMS_PASSWORD' => $smsPassword,
            'WHATSAPP_ENABLED' => $whatsappNotificationsEnabled ? 'true' : 'false',
            'WHATSAPP_INSTANCE_ID' => $whatsappInstanceId,
            'WHATSAPP_API_TOKEN' => $whatsappApiToken,
            'PUSH_ENABLED' => $pushNotificationsEnabled ? 'true' : 'false',
            'VAPID_PUBLIC_KEY' => $vapidPublicKey,
            'VAPID_PRIVATE_KEY' => $vapidPrivateKey
        ]);
        
        echo json_encode(['success' => true, 'message' => trans('settings_updated_successfully')]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Error saving notification settings: ' . $e->getMessage()]);
    }
}

function handleSaveAppSettings() {
    global $db;
    
    try {
        $appDebug = isset($_POST['app_debug']) ? 1 : 0;
        $appUrl = $_POST['app_url'] ?? '';
        $appKey = $_POST['app_key'] ?? '';
        
        // Update .env file if possible
        updateEnvFile([
            'APP_DEBUG' => $appDebug ? 'true' : 'false',
            'APP_URL' => $appUrl,
            'APP_KEY' => $appKey
        ]);
        
        echo json_encode(['success' => true, 'message' => 'Application settings updated successfully']);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Error saving application settings: ' . $e->getMessage()]);
    }
}

function handleSaveDatabaseSettings() {
    global $db;
    
    try {
        $dbHost = $_POST['db_host'] ?? '';
        $dbPort = $_POST['db_port'] ?? '3306';
        $dbName = $_POST['db_name'] ?? '';
        $dbUser = $_POST['db_user'] ?? '';
        $dbPassword = $_POST['db_password'] ?? '';
        
        // Update .env file if possible
        $envData = [
            'DB_HOST' => $dbHost,
            'DB_PORT' => $dbPort,
            'DB_NAME' => $dbName,
            'DB_USER' => $dbUser
        ];
        
        // Only update password if provided
        if (!empty($dbPassword)) {
            $envData['DB_PASSWORD'] = $dbPassword;
        }
        
        updateEnvFile($envData);
        
        echo json_encode(['success' => true, 'message' => 'Database settings updated successfully']);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Error saving database settings: ' . $e->getMessage()]);
    }
}

function handleSavePaymentGatewaySettings() {
    global $db;
    
    try {
        $campayApiToken = $_POST['campay_api_token'] ?? '';
        
        // Update settings table
        $db->query(
            "UPDATE settings SET campay_api_token = ? LIMIT 1",
            [$campayApiToken]
        );
        
        echo json_encode(['success' => true, 'message' => 'Payment gateway settings updated successfully']);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Error saving payment gateway settings: ' . $e->getMessage()]);
    }
}

// Helper functions
function handleFileUpload($file, $type) {
    $uploadDir = SSCI_PUBLIC . '/uploads/' . $type . '/';
    
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }
    
    $filename = uniqid() . '_' . basename($file['name']);
    $filepath = $uploadDir . $filename;
    
    if (move_uploaded_file($file['tmp_name'], $filepath)) {
        return '/public/uploads/' . $type . '/' . $filename;
    }
    
    throw new Exception('Failed to upload file');
}

function updateEnvFile($data) {
    $envPath = SSCI_ROOT . '/.env';
    
    if (!file_exists($envPath)) {
        return false;
    }
    
    $content = file_get_contents($envPath);
    
    foreach ($data as $key => $value) {
        $pattern = '/^' . preg_quote($key) . '=.*$/m';
        $replacement = $key . '=' . $value;
        
        if (preg_match($pattern, $content)) {
            $content = preg_replace($pattern, $replacement, $content);
        } else {
            $content .= "\n" . $replacement;
        }
    }
    
    return file_put_contents($envPath, $content) !== false;
}

function updateConfigCache($data) {
    // This would update the config cache if you have a caching mechanism
    // For now, we'll skip this since the config is read from .env
}

