<?php
/**
 * WhatsApp Settings API
 * 
 * Handles fetching and saving WhatsApp configuration and .env variables.
 */
session_start();
require_once __DIR__ . '/../libs/classes/DbPathsArray.php';
require_once __DIR__ . '/../libs/classes/App_DB.php';
require_once __DIR__ . '/../libs/classes/EnvLoader.php';

$crud = new App_DB(DBU::$dba_user);

if (!isset($_SESSION['userid'])) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

$action = $_REQUEST['action'] ?? '';

// Ensure whatsapp_enabled column exists
try {
    $crud->dbQuery("SELECT whatsapp_enabled FROM config LIMIT 1");
} catch (Exception $e) {
    $crud->dbQuery("ALTER TABLE config ADD COLUMN whatsapp_enabled TINYINT(1) DEFAULT 0");
}

header('Content-Type: application/json');

switch ($action) {
    case 'fetchSettings':
        $config = $crud->getRecordSet("SELECT whatsapp_enabled FROM config LIMIT 1");
        $enabled = !empty($config) ? (bool) $config[0]['whatsapp_enabled'] : false;

        echo json_encode([
            'success' => true,
            'whatsapp_enabled' => $enabled,
            'whatsapp_instance_id' => EnvLoader::get('WHATSAPP_INSTANCE_ID', ''),
            'whatsapp_token' => EnvLoader::get('WHATSAPP_TOKEN', '')
        ]);
        break;

    case 'saveSettings':
        $enabled = isset($_POST['whatsapp_enabled']) ? (int) $_POST['whatsapp_enabled'] : 0;
        $instanceId = $_POST['whatsapp_instance_id'] ?? '';
        $token = $_POST['whatsapp_token'] ?? '';

        // Validation: Cannot enable if credentials are missing
        if ($enabled && (empty($instanceId) || empty($token))) {
            echo json_encode(['success' => false, 'message' => 'WhatsApp cannot be enabled without Instance ID and Token.']);
            exit;
        }

        // 1. Update DB
        $crud->dbQuery("UPDATE config SET whatsapp_enabled = $enabled");

        // 2. Update .env
        $envFile = __DIR__ . '/../../.env';
        if (file_exists($envFile)) {
            $envContent = file_get_contents($envFile);

            // Function to update or add env variable
            $updateEnv = function ($content, $key, $value) {
                $pattern = "/^" . preg_quote($key) . "=.*/m";
                $newLine = "{$key}={$value}";
                if (preg_match($pattern, $content)) {
                    return preg_replace($pattern, $newLine, $content);
                } else {
                    return $content . "\n" . $newLine;
                }
            };

            $envContent = $updateEnv($envContent, 'WHATSAPP_INSTANCE_ID', $instanceId);
            $envContent = $updateEnv($envContent, 'WHATSAPP_TOKEN', $token);

            if (file_put_contents($envFile, $envContent) === false) {
                echo json_encode(['success' => false, 'message' => 'Failed to write to .env file. Please check permissions.']);
                exit;
            }
        }

        echo json_encode(['success' => true, 'message' => 'Settings saved successfully.']);
        break;

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