<?php

require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/database.php';

require_login();

// Control de seguridad por Rol (Estandarizado)
require_once '../../core/permissions.php';

if (current_user_role() !== 'admin') {
    header('Location: /modules/dashboard/');
    exit;
}

$pdo = db();

// Recepción de Datos
$name    = isset($_POST['company_name']) ? trim($_POST['company_name']) : '';
$taxId   = isset($_POST['company_tax_id']) ? trim($_POST['company_tax_id']) : '';
$giro    = isset($_POST['company_giro']) ? trim($_POST['company_giro']) : '';
$address = isset($_POST['company_address']) ? trim($_POST['company_address']) : '';
$comuna  = isset($_POST['company_comuna']) ? trim($_POST['company_comuna']) : '';
$ciudad  = isset($_POST['company_ciudad']) ? trim($_POST['company_ciudad']) : '';
$phone   = isset($_POST['company_phone']) ? trim($_POST['company_phone']) : '';
$email   = isset($_POST['company_email']) ? trim($_POST['company_email']) : '';
$web     = isset($_POST['company_website']) ? trim($_POST['company_website']) : '';

$bName   = isset($_POST['bank_name']) ? trim($_POST['bank_name']) : '';
$bType   = isset($_POST['bank_account_type']) ? trim($_POST['bank_account_type']) : '';
$bNum    = isset($_POST['bank_account_number']) ? trim($_POST['bank_account_number']) : '';
$bHolder = isset($_POST['bank_holder_name']) ? trim($_POST['bank_holder_name']) : '';
$bRut    = isset($_POST['bank_holder_tax_id']) ? trim($_POST['bank_holder_tax_id']) : '';
$bEmail  = isset($_POST['bank_email']) ? trim($_POST['bank_email']) : '';

// Procesar Configuración de Módulos
$modules_config = [];
$mod_keys = $_POST['mod_key'] ?? [];
$mod_titles = $_POST['mod_title'] ?? [];
$mod_sections = $_POST['mod_section'] ?? [];
$mod_icons = $_POST['mod_icon'] ?? [];
$mod_orders = $_POST['mod_order'] ?? [];
$mod_actives = $_POST['mod_active'] ?? [];

foreach ($mod_keys as $index => $key) {
    $modules_config[$key] = [
        'title' => trim($mod_titles[$index]),
        'section' => trim($mod_sections[$index]),
        'icon' => trim($mod_icons[$index]),
        'order' => (int)($mod_orders[$index]),
        'is_active' => isset($mod_actives[$key]) ? 1 : 0
    ];
}
$modules_json = json_encode($modules_config);

$errors = array();

// Validaciones
if ($name === '')    $errors['company_name'] = 'Debe ingresar la razón social.';
if ($taxId === '')   $errors['company_tax_id'] = 'Debe indicar el RUT de la empresa.';
if ($giro === '')    $errors['company_giro'] = 'Debe detallar el giro comercial.';
if ($address === '') $errors['company_address'] = 'Debe indicar la dirección.';
if ($comuna === '')  $errors['company_comuna'] = 'Debe ingresar la comuna.';
if ($ciudad === '')  $errors['company_ciudad'] = 'Debe indicar la ciudad.';
if ($phone === '')   $errors['company_phone'] = 'Debe ingresar un teléfono.';
if ($email === '')   $errors['company_email'] = 'Debe ingresar un correo institucional.';

if ($bName === '')   $errors['bank_name'] = 'Indique el nombre del banco.';
if ($bType === '')   $errors['bank_account_type'] = 'Especifique el tipo de cuenta.';
if ($bNum === '')    $errors['bank_account_number'] = 'Ingrese el número de cuenta.';
if ($bHolder === '') $errors['bank_holder_name'] = 'Indique el nombre del titular.';
if ($bRut === '')    $errors['bank_holder_tax_id'] = 'Indique el RUT del titular.';
if ($bEmail === '')  $errors['bank_email'] = 'Ingrese un correo para avisos.';

// Tratamiento de Logotipo
$logoPath = null;
if (isset($_FILES['company_logo']) && $_FILES['company_logo']['error'] === UPLOAD_ERR_OK) {
    $fileTmpPath = $_FILES['company_logo']['tmp_name'];
    $fileName = $_FILES['company_logo']['name'];
    $fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
    
    if (in_array($fileExtension, array('jpg', 'jpeg', 'png'))) {
        $uploadDir = '../../assets/uploads/';
        if (!is_dir($uploadDir)) { mkdir($uploadDir, 0755, true); }
        
        $newFileName = 'logo_corporativo.' . $fileExtension;
        $destPath = $uploadDir . $newFileName;
        
        if (move_uploaded_file($fileTmpPath, $destPath)) {
            $logoPath = '/assets/uploads/' . $newFileName;
        }
    }
}

if (!empty($errors)) {
    $_SESSION['form_errors'] = $errors;
    $_SESSION['form_old'] = $_POST;
    header('Location: /modules/admin/company_settings.php');
    exit;
}

try {
    $sql = "UPDATE system_settings SET 
                company_name = ?, company_tax_id = ?, company_giro = ?, company_address = ?, 
                company_comuna = ?, company_ciudad = ?, company_phone = ?, company_email = ?, company_website = ?,
                bank_name = ?, bank_account_type = ?, bank_account_number = ?, bank_holder_name = ?, bank_holder_tax_id = ?, bank_email = ?,
                modules_config = ?"; // <-- Columna añadida
    
    $params = array($name, $taxId, $giro, $address, $comuna, $ciudad, $phone, $email, $web, $bName, $bType, $bNum, $bHolder, $bRut, $bEmail, $modules_json); // <-- Variable añadida

    if ($logoPath !== null) {
        $sql .= ", company_logo = ?";
        $params[] = $logoPath;
    }

    $sql .= " WHERE id = 1";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);

    header('Location: /modules/admin/company_settings.php?success=1');
    exit;

} catch (Exception $e) {
    die("Error al guardar configuraciones: " . $e->getMessage());
}