<?php
session_start();

require '../../config.php';
require '../admin_config.php';
require '../functions.php';

// Check if user is logged in
if (!isset($_SESSION['user_email'])) {
    header('Location: ../login.php');
    exit();
}

$connect = connect($database);
$check_access = check_access($connect);

if ($check_access['user_role'] != 1 && $check_access['user_role'] != 2) {
    header('Location: ../login.php');
    exit();
}

$user = $check_access;

$message = '';
$error = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $cuelinks_email = trim($_POST['cuelinks_email'] ?? '');
    $cuelinks_api_key = trim($_POST['cuelinks_api_key'] ?? '');
    $cuelinks_enabled = isset($_POST['cuelinks_enabled']) ? 1 : 0;
    
    try {
        // Check if settings exist
        $check = $connect->prepare("SELECT COUNT(*) FROM settings WHERE st_id = 1");
        $check->execute();
        
        // Update or insert CueLinks settings
        $stmt = $connect->prepare("
            UPDATE settings 
            SET cuelinks_email = ?, 
                cuelinks_api_key = ?, 
                cuelinks_enabled = ?
            WHERE st_id = 1
        ");
        
        if ($stmt->execute([$cuelinks_email, $cuelinks_api_key, $cuelinks_enabled])) {
            $message = 'CueLinks configuration saved successfully!';
        } else {
            $error = 'Failed to save configuration.';
        }
    } catch (PDOException $e) {
        $error = 'Database error: ' . $e->getMessage();
    }
}

// Fetch current settings
try {
    $stmt = $connect->prepare("SELECT cuelinks_email, cuelinks_api_key, cuelinks_enabled FROM settings WHERE st_id = 1");
    $stmt->execute();
    $settings = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$settings) {
        $settings = [
            'cuelinks_email' => '',
            'cuelinks_api_key' => '',
            'cuelinks_enabled' => 0
        ];
    }
} catch (PDOException $e) {
    $error = 'Failed to load settings: ' . $e->getMessage();
    $settings = [
        'cuelinks_email' => '',
        'cuelinks_api_key' => '',
        'cuelinks_enabled' => 0
    ];
}

require '../views/cuelinks_config.view.php';
?>
