<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/../includes/helpers.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

check_role('administrador');

$user = get_logged_in_user();

$error = '';
$success = '';
$csrf_token = get_csrf_token();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Validate CSRF token
    if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
        $error = 'Token de seguridad inválido.';
    } else {
        $username = trim($_POST['username']);
        $email = trim($_POST['email']);
        $password = $_POST['password'];
        $first_name = trim($_POST['first_name']);
        $last_name = trim($_POST['last_name']);
        $company_name = trim($_POST['company_name']);
        $phone = trim($_POST['phone']);
        $address = trim($_POST['address']);
        $website = trim($_POST['website']);
        $description = trim($_POST['description']);

        if (empty($username) || empty($email) || empty($password) || empty($company_name) || empty($first_name) || empty($last_name)) {
            $error = 'Por favor, rellene todos los campos obligatorios.';
        }

        // Handle photo upload (optional)
        $photo_path = null;
        if (!$error && isset($_FILES['photo']) && $_FILES['photo']['error'] == 0) {
            $allowed_types = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
            $max_size = 2 * 1024 * 1024; // 2MB

            if (!in_array($_FILES['photo']['type'], $allowed_types)) {
                $error = 'Tipo de archivo inválido para la foto. Solo se permiten JPG, PNG y GIF.';
            } elseif ($_FILES['photo']['size'] > $max_size) {
                $error = 'La foto es demasiado grande. El tamaño máximo es 2MB.';
            } else {
                $upload_dir = BASE_PATH . '/uploads/photos/';
                if (!is_dir($upload_dir)) {
                    mkdir($upload_dir, 0777, true);
                }

                $file_extension = strtolower(pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION));
                $file_name = uniqid('user_') . '.' . $file_extension;
                $file_path = $upload_dir . $file_name;

                if (move_uploaded_file($_FILES['photo']['tmp_name'], $file_path)) {
                    $photo_path = 'uploads/photos/' . $file_name;
                } else {
                    // Try alternative approach - copy file instead of move
                    if (copy($_FILES['photo']['tmp_name'], $file_path)) {
                        $photo_path = 'uploads/photos/' . $file_name;
                    } else {
                        $error = 'Error al subir la foto. Problemas de permisos en el directorio. Ejecute: chmod -R 777 uploads/ o contacte al administrador del sistema.';
                    }
                }
            }
        }

        // Handle logo upload (optional)
        $logo_path = null;
        if (!$error && isset($_FILES['logo']) && $_FILES['logo']['error'] == 0) {
            $allowed_types = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
            $max_size = 2 * 1024 * 1024; // 2MB

            if (!in_array($_FILES['logo']['type'], $allowed_types)) {
                $error = 'Tipo de archivo inválido para el logo. Solo se permiten JPG, PNG y GIF.';
            } elseif ($_FILES['logo']['size'] > $max_size) {
                $error = 'El logo es demasiado grande. El tamaño máximo es 2MB.';
            } else {
                $upload_dir = BASE_PATH . '/uploads/logos/';
                if (!is_dir($upload_dir)) {
                    mkdir($upload_dir, 0777, true);
                }

                $file_extension = strtolower(pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION));
                $file_name = uniqid('company_') . '.' . $file_extension;
                $file_path = $upload_dir . $file_name;

                if (move_uploaded_file($_FILES['logo']['tmp_name'], $file_path)) {
                    $logo_path = 'uploads/logos/' . $file_name;
                } else {
                    // Try alternative approach - copy file instead of move
                    if (copy($_FILES['logo']['tmp_name'], $file_path)) {
                        $logo_path = 'uploads/logos/' . $file_name;
                    } else {
                        $error = 'Error al subir el logo. Problemas de permisos en el directorio. Ejecute: chmod -R 777 uploads/ o contacte al administrador del sistema.';
                    }
                }
            }
        }

        if (!$error) {
            // Check if username or email exists
            $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
            $stmt->execute([$username, $email]);
            if ($stmt->fetch()) {
                $error = 'El nombre de usuario o correo electrónico ya existe.';
            } else {
                // Insert user
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("INSERT INTO users (username, password, email, role_id, first_name, last_name, photo) VALUES (?, ?, ?, 4, ?, ?, ?)");
                if ($stmt->execute([$username, $hashed_password, $email, $first_name, $last_name, $photo_path])) {
                    $user_id = $pdo->lastInsertId();

                    // Log user creation
                    audit_user_creation([
                        'id' => $user_id,
                        'username' => $username,
                        'email' => $email,
                        'role_id' => 4,
                        'first_name' => $first_name,
                        'last_name' => $last_name
                    ]);

                    // Insert into companies table
                    $stmt = $pdo->prepare("INSERT INTO companies (user_id, company_name, phone, address, website, description, logo) VALUES (?, ?, ?, ?, ?, ?, ?)");
                    $stmt->execute([$user_id, $company_name, $phone, $address, $website, $description, $logo_path]);

                    $success = 'Empresa agregada exitosamente.';
                } else {
                    $error = 'No se pudo agregar la empresa.';
                }
            }
        }
    }
}

$page_title = 'Agregar Empresa';

$error_alert = $error ? '<div class="alert alert-danger">' . htmlspecialchars($error) . '</div>' : '';
$success_alert = $success ? '<div class="alert alert-success">' . htmlspecialchars($success) . '</div>' : '';

$content = <<<HTML
<div class="row">
    <div class="col-md-8">
        <div class="card card-primary">
            <div class="card-header">
                <h3 class="card-title">Agregar nueva empresa</h3>
            </div>
            <form method="post" enctype="multipart/form-data">
                <input type="hidden" name="csrf_token" value="{$csrf_token}" />
                <div class="card-body">
                    {$error_alert}
                    {$success_alert}
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="username">Nombre de Usuario *</label>
                                <input type="text" class="form-control" id="username" name="username" required>
                                <small class="form-text text-muted">Nombre único para iniciar sesión</small>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="email">Correo Electrónico *</label>
                                <input type="email" class="form-control" id="email" name="email" required>
                                <small class="form-text text-muted">Será usado para notificaciones</small>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="first_name">Nombres del Contacto *</label>
                                <input type="text" class="form-control" id="first_name" name="first_name" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="last_name">Apellidos del Contacto *</label>
                                <input type="text" class="form-control" id="last_name" name="last_name" required>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="password">Contraseña *</label>
                                <input type="password" class="form-control" id="password" name="password" required>
                                <small class="form-text text-muted">Mínimo 6 caracteres</small>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="photo">Foto del Contacto</label>
                                <input type="file" class="form-control" id="photo" name="photo" accept="image/*">
                                <small class="form-text text-muted">JPG, PNG, GIF. Máx 2MB</small>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="company_name">Nombre de la Empresa *</label>
                        <input type="text" class="form-control" id="company_name" name="company_name" required>
                        <small class="form-text text-muted">Nombre oficial de la empresa</small>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="phone">Teléfono</label>
                                <input type="tel" class="form-control" id="phone" name="phone" placeholder="Número de teléfono">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="logo">Logo de la Empresa</label>
                                <input type="file" class="form-control" id="logo" name="logo" accept="image/*">
                                <small class="form-text text-muted">JPG, PNG, GIF. Máx 2MB</small>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="address">Dirección</label>
                        <input type="text" class="form-control" id="address" name="address" placeholder="Dirección completa de la empresa">
                    </div>

                    <div class="form-group">
                        <label for="website">Sitio Web</label>
                        <input type="url" class="form-control" id="website" name="website" placeholder="https://www.ejemplo.com">
                        <small class="form-text text-muted">URL completa incluyendo https://</small>
                    </div>

                    <div class="form-group">
                        <label for="description">Descripción</label>
                        <textarea class="form-control" id="description" name="description" rows="4" placeholder="Describe la empresa, su misión, visión, productos/servicios, etc."></textarea>
                        <small class="form-text text-muted">Describe la empresa y sus actividades</small>
                    </div>
                </div>

                <div class="card-footer">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> Agregar Empresa
                    </button>
                    <button type="button" onclick="window.history.back()" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> Volver
                    </button>
                </div>
            </form>
        </div>
    </div>

    <div class="col-md-4">
        <div class="card card-info">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-info-circle"></i> Información
                </h3>
            </div>
            <div class="card-body">
                <h5>Campos Obligatorios</h5>
                <ul class="list-unstyled">
                    <li><i class="fas fa-check text-success"></i> Nombre de usuario</li>
                    <li><i class="fas fa-check text-success"></i> Correo electrónico</li>
                    <li><i class="fas fa-check text-success"></i> Contraseña</li>
                    <li><i class="fas fa-check text-success"></i> Nombres del contacto</li>
                    <li><i class="fas fa-check text-success"></i> Apellidos del contacto</li>
                    <li><i class="fas fa-check text-success"></i> Nombre de la empresa</li>
                </ul>

                <h5 class="mt-3">Campos Opcionales</h5>
                <ul class="list-unstyled">
                    <li><i class="fas fa-circle text-muted"></i> Foto del contacto</li>
                    <li><i class="fas fa-circle text-muted"></i> Teléfono</li>
                    <li><i class="fas fa-circle text-muted"></i> Logo de la empresa</li>
                    <li><i class="fas fa-circle text-muted"></i> Dirección</li>
                    <li><i class="fas fa-circle text-muted"></i> Sitio web</li>
                    <li><i class="fas fa-circle text-muted"></i> Descripción</li>
                </ul>

                <div class="alert alert-warning mt-3">
                    <i class="fas fa-exclamation-triangle"></i>
                    <strong>Nota:</strong> La empresa podrá completar su perfil más tarde desde su panel de empresa.
                </div>
            </div>
        </div>
    </div>
</div>

<script src="<?php echo url('assets/js/add-user.js'); ?>"></script>
<script>
// Additional company-specific JavaScript
document.addEventListener('DOMContentLoaded', function() {
    // Enhanced form validation for company
    const form = document.querySelector('form');
    form.addEventListener('submit', function(e) {
        const companyName = document.getElementById('company_name').value.trim();

        if (!companyName) {
            e.preventDefault();
            alert('Por favor, ingrese el nombre de la empresa.');
            document.getElementById('company_name').focus();
            return false;
        }

        // Validate website URL if provided
        const website = document.getElementById('website').value.trim();
        if (website && !website.match(/^https?:\/\/.+/)) {
            e.preventDefault();
            alert('La URL del sitio web debe comenzar con http:// o https://');
            document.getElementById('website').focus();
            return false;
        }

        return true;
    });

    console.log('Add Company JavaScript loaded successfully');
});
</script>
HTML;

include BASE_PATH . '/includes/layout.php';
?>