<?php
$section = 'company_profile';
require_once __DIR__ . '/db/config.php';
require_once __DIR__ . '/helpers.php';

require_once __DIR__ . '/includes/auth.php';
check_auth();

$db = db();
$lang = $_SESSION['lang'];
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    foreach ($_POST as $key => $value) {
        if ($key !== 'submit') {
            // Use INSERT ... ON DUPLICATE KEY UPDATE to handle both new and existing settings
            $stmt = $db->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");
            $stmt->execute([$key, $value]);
        }
    }

    // Handle File Uploads (Logo & Favicon)
    $upload_dir = __DIR__ . '/assets/images/';
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0775, true);
    }

    if (isset($_FILES['company_logo']) && $_FILES['company_logo']['error'] === UPLOAD_ERR_OK) {
        $ext = pathinfo($_FILES['company_logo']['name'], PATHINFO_EXTENSION);
        $logo_name = 'logo_' . time() . '.' . $ext;
        move_uploaded_file($_FILES['company_logo']['tmp_name'], $upload_dir . $logo_name);
        
        $stmt = $db->prepare("INSERT INTO settings (setting_key, setting_value) VALUES ('company_logo', ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");
        $stmt->execute(['assets/images/' . $logo_name]);
    }

    if (isset($_FILES['company_favicon']) && $_FILES['company_favicon']['error'] === UPLOAD_ERR_OK) {
        $ext = pathinfo($_FILES['company_favicon']['name'], PATHINFO_EXTENSION);
        $favicon_name = 'favicon_' . time() . '.' . $ext;
        move_uploaded_file($_FILES['company_favicon']['tmp_name'], $upload_dir . $favicon_name);
        
        $stmt = $db->prepare("INSERT INTO settings (setting_key, setting_value) VALUES ('company_favicon', ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");
        $stmt->execute(['assets/images/' . $favicon_name]);
    }

    $message = __('settings_updated_successfully');
}

// Fetch all settings
$stmt = $db->query("SELECT setting_key, setting_value FROM settings");
$settings = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $settings[$row['setting_key']] = $row['setting_value'];
}

require_once __DIR__ . '/includes/actions.php';
require_once __DIR__ . '/includes/common_data.php';
require_once __DIR__ . '/includes/layout/header.php';
require_once __DIR__ . '/includes/pages/settings.php';
require_once __DIR__ . '/includes/layout/footer.php';