<?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']) : '';
$commercialFooter = isset($_POST['commercial_document_footer']) ? trim(str_replace(array("\r\n", "\r"), "\n", (string)$_POST['commercial_document_footer'])) : '';
$quoteDefaultConditions = isset($_POST['quote_default_conditions']) ? trim(str_replace(array("\r\n", "\r"), "\n", (string)$_POST['quote_default_conditions'])) : '';
$purchaseOrderDefaultTerms = isset($_POST['purchase_order_default_terms']) ? trim(str_replace(array("\r\n", "\r"), "\n", (string)$_POST['purchase_order_default_terms'])) : '';

// 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.';
if ((function_exists('mb_strlen') ? mb_strlen($commercialFooter, 'UTF-8') : strlen($commercialFooter)) > 500) {
    $errors['commercial_document_footer'] = 'El pie de documentos comerciales no puede superar 500 caracteres.';
}
if ((function_exists('mb_strlen') ? mb_strlen($quoteDefaultConditions, 'UTF-8') : strlen($quoteDefaultConditions)) > 1000) {
    $errors['quote_default_conditions'] = 'Las condiciones predeterminadas de cotización no pueden superar 1.000 caracteres.';
}
if ((function_exists('mb_strlen') ? mb_strlen($purchaseOrderDefaultTerms, 'UTF-8') : strlen($purchaseOrderDefaultTerms)) > 2000) {
    $errors['purchase_order_default_terms'] = 'Las condiciones predeterminadas de órdenes de compra no pueden superar 2.000 caracteres.';
}

csrf_require_valid_request();

// Tratamiento de Logotipo
$logoPath = null;
if (isset($_FILES['company_logo']) && $_FILES['company_logo']['error'] === UPLOAD_ERR_OK) {
    $fileTmpPath = $_FILES['company_logo']['tmp_name'];
    $fileSize = (int)$_FILES['company_logo']['size'];
    $imageInfo = ($fileSize > 0 && $fileSize <= 5 * 1024 * 1024 && is_uploaded_file($fileTmpPath))
        ? @getimagesize($fileTmpPath)
        : false;
    $allowedImageTypes = array(
        IMAGETYPE_JPEG => 'jpg',
        IMAGETYPE_PNG => 'png'
    );

    if ($imageInfo !== false && isset($allowedImageTypes[$imageInfo[2]])) {
        $fileExtension = $allowedImageTypes[$imageInfo[2]];
        $uploadDir = '../../assets/uploads/';
        if (!is_dir($uploadDir) && !mkdir($uploadDir, 0750, true) && !is_dir($uploadDir)) {
            $errors['company_logo'] = 'No se pudo preparar el directorio del logotipo.';
        }
        
        $newFileName = 'logo_corporativo.' . $fileExtension;
        $destPath = $uploadDir . $newFileName;
        
        if (empty($errors['company_logo']) && move_uploaded_file($fileTmpPath, $destPath)) {
            @chmod($destPath, 0640);
            $logoPath = '/assets/uploads/' . $newFileName;
        } elseif (empty($errors['company_logo'])) {
            $errors['company_logo'] = 'No fue posible guardar el logotipo.';
        }
    } else {
        $errors['company_logo'] = 'El logotipo debe ser una imagen JPEG o PNG válida de hasta 5 MB.';
    }
}

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 = ?,
                commercial_document_footer = ?, quote_default_conditions = ?, purchase_order_default_terms = ?, modules_config = ?";
    
    $params = array($name, $taxId, $giro, $address, $comuna, $ciudad, $phone, $email, $web, $bName, $bType, $bNum, $bHolder, $bRut, $bEmail, $commercialFooter, $quoteDefaultConditions, $purchaseOrderDefaultTerms, $modules_json);

    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());
}
