<?php
header('Content-Type: application/json');
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/auth.php';

if (!isLoggedIn() || getCurrentUser()['role'] !== 'admin') {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Unauthorized.']);
    exit();
}

$action = $_GET['action'] ?? $_POST['action'] ?? '';

if ($action === 'status') {
    try {
        $stmt = $pdo->query("SELECT key, value FROM system_settings WHERE key IN ('gdrive_connected', 'gdrive_account_email', 'onedrive_connected', 'onedrive_account_email')");
        $configs = $stmt->fetchAll(PDO::FETCH_KEY_PAIR) ?: [];

        echo json_encode([
            'success' => true,
            'gdrive' => [
                'connected' => ($configs['gdrive_connected'] ?? '0') === '1',
                'email' => $configs['gdrive_account_email'] ?? ''
            ],
            'onedrive' => [
                'connected' => ($configs['onedrive_connected'] ?? '0') === '1',
                'email' => $configs['onedrive_account_email'] ?? ''
            ]
        ]);
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
    }
    exit();
} elseif ($action === 'connect') {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
        exit();
    }
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        echo json_encode(['success' => false, 'message' => 'Security check failed (CSRF).']);
        exit();
    }

    $provider = trim($_POST['provider'] ?? '');
    if ($provider !== 'gdrive' && $provider !== 'onedrive') {
        echo json_encode(['success' => false, 'message' => 'Invalid cloud provider.']);
        exit();
    }

    $email = ($provider === 'gdrive') ? GDRIVE_DEFAULT_EMAIL : ONEDRIVE_DEFAULT_EMAIL;

    try {
        $pdo->beginTransaction();
        $stmt = $pdo->prepare("INSERT INTO system_settings (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value");
        
        $stmt->execute(["{$provider}_connected", '1']);
        $stmt->execute(["{$provider}_account_email", $email]);

        $pdo->commit();
        echo json_encode([
            'success' => true, 
            'message' => ucfirst($provider === 'gdrive' ? 'Google Drive' : 'OneDrive') . ' successfully connected.',
            'email' => $email
        ]);
    } catch (PDOException $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
    }
    exit();
} elseif ($action === 'disconnect') {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
        exit();
    }
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        echo json_encode(['success' => false, 'message' => 'Security check failed (CSRF).']);
        exit();
    }

    $provider = trim($_POST['provider'] ?? '');
    if ($provider !== 'gdrive' && $provider !== 'onedrive') {
        echo json_encode(['success' => false, 'message' => 'Invalid cloud provider.']);
        exit();
    }

    try {
        $pdo->beginTransaction();
        $stmt = $pdo->prepare("DELETE FROM system_settings WHERE key IN (?, ?)");
        $stmt->execute(["{$provider}_connected", "{$provider}_account_email"]);

        $pdo->commit();
        echo json_encode(['success' => true, 'message' => ucfirst($provider === 'gdrive' ? 'Google Drive' : 'OneDrive') . ' disconnected successfully.']);
    } catch (PDOException $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
    }
    exit();
}

echo json_encode(['success' => false, 'message' => 'Invalid action.']);
