<?php
require '../../app/db.php';
require '../includes/auth.php';



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

if ($_SESSION['admin_role'] !== 'superadmin') {
    echo json_encode(['success'=>false,'error'=>'Unauthorized']);
    exit;
}

try {

    // Update text settings
    foreach ($_POST as $key => $value) {

        $stmt = $pdo->prepare("
        UPDATE system_settings
        SET setting_value=?
        WHERE setting_key=?
        ");

        $stmt->execute([
            trim($value),
            $key
        ]);
    }

    // Logo Upload Handling
    if (isset($_FILES['company_logo']) 
        && $_FILES['company_logo']['error'] === 0) {

        $allowedTypes = [
            'image/jpeg',
            'image/png',
            'image/svg+xml'
        ];

        if (!in_array(
            $_FILES['company_logo']['type'],
            $allowedTypes
        )) {
            throw new Exception("Invalid file type.");
        }

        if ($_FILES['company_logo']['size'] > 2 * 1024 * 1024) {
            throw new Exception("File exceeds 2MB.");
        }

        $extension = pathinfo(
            $_FILES['company_logo']['name'],
            PATHINFO_EXTENSION
        );

        $filename = 'logo_' . time() . '.' . $extension;

        $uploadPath = '../uploads/logo/' . $filename;

        if (!move_uploaded_file(
            $_FILES['company_logo']['tmp_name'],
            $uploadPath
        )) {
            throw new Exception("Upload failed.");
        }

        // Delete old logo
        $stmt = $pdo->prepare("
        SELECT setting_value
        FROM system_settings
        WHERE setting_key='company_logo'
        ");
        $stmt->execute();
        $oldLogo = $stmt->fetchColumn();

        if ($oldLogo && file_exists('../uploads/logo/'.$oldLogo)) {
            unlink('../uploads/logo/'.$oldLogo);
        }

        // Update DB
        $pdo->prepare("
        UPDATE system_settings
        SET setting_value=?
        WHERE setting_key='company_logo'
        ")->execute([$filename]);
    }

    echo json_encode(['success'=>true]);

} catch (Exception $e) {

    echo json_encode([
        'success'=>false,
        'error'=>$e->getMessage()
    ]);
}
