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

$user_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$user_id) {
    header('Location: companies.php');
    exit;
}

// Get user details
$stmt = $pdo->prepare("SELECT u.*, r.name as role_name FROM users u JOIN roles r ON u.role_id = r.id WHERE u.id = ?");
$stmt->execute([$user_id]);
$user_data = $stmt->fetch();

if (!$user_data || $user_data['role_name'] !== 'empresa') {
    header('Location: companies.php');
    exit;
}

// Get company-specific information
$stmt = $pdo->prepare("SELECT * FROM companies WHERE user_id = ?");
$stmt->execute([$user_id]);
$company_info = $stmt->fetch();

$error = '';
$success = '';

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']);
        $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($company_name)) {
            $error = 'Se requieren nombre de usuario, correo electrónico y nombre de empresa.';
        } else {
            // Check if username or email exists (excluding current user)
            $stmt = $pdo->prepare("SELECT id FROM users WHERE (username = ? OR email = ?) AND id != ?");
            $stmt->execute([$username, $email, $user_id]);
            if ($stmt->fetch()) {
                $error = 'El nombre de usuario o correo electrónico ya existe.';
            } else {
                // Handle photo upload (optional)
                $photo_path = $user_data['photo'];
                if (!$error && isset($_FILES['photo']) && $_FILES['photo']['error'] == 0) {
                    $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
                    if (in_array($_FILES['photo']['type'], $allowed_types) && $_FILES['photo']['size'] <= 2097152) { // 2MB
                        $upload_dir = BASE_PATH . '/uploads/photos/';
                        if (!is_dir($upload_dir)) {
                            mkdir($upload_dir, 0777, true);
                        }
                        $file_extension = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
                        $file_name = uniqid() . '.' . $file_extension;
                        $file_path = $upload_dir . $file_name;

                        if (move_uploaded_file($_FILES['photo']['tmp_name'], $file_path)) {
                            // Delete old photo if exists
                            if ($photo_path && file_exists(BASE_PATH . '/' . $photo_path)) {
                                unlink(BASE_PATH . '/' . $photo_path);
                            }
                            $photo_path = 'uploads/photos/' . $file_name;
                        }
                    }
                }

                // Handle logo upload (optional)
                $logo_path = $company_info['logo'];
                if (!$error && isset($_FILES['logo']) && $_FILES['logo']['error'] == 0) {
                    $allowed_types = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
                    if (in_array($_FILES['logo']['type'], $allowed_types) && $_FILES['logo']['size'] <= 2097152) { // 2MB
                        $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() . '.' . $file_extension;
                        $file_path = $upload_dir . $file_name;

                        if (move_uploaded_file($_FILES['logo']['tmp_name'], $file_path)) {
                            // Delete old logo if exists
                            if ($logo_path && file_exists(BASE_PATH . '/' . $logo_path)) {
                                unlink(BASE_PATH . '/' . $logo_path);
                            }
                            $logo_path = 'uploads/logos/' . $file_name;
                        }
                    }
                }

                if (!$error) {
                    // Update user
                    $stmt = $pdo->prepare("UPDATE users SET username = ?, email = ?, first_name = ?, last_name = ?, photo = ? WHERE id = ?");
                    if ($stmt->execute([$username, $email, $first_name, $last_name, $photo_path, $user_id])) {
                        // Update company information
                        $stmt = $pdo->prepare("UPDATE companies SET company_name = ?, phone = ?, address = ?, website = ?, description = ?, logo = ? WHERE user_id = ?");
                        $stmt->execute([
                            $company_name,
                            $phone ?: null,
                            $address ?: null,
                            $website ?: null,
                            $description ?: null,
                            $logo_path,
                            $user_id
                        ]);

                        $success = 'Empresa actualizada con éxito.';
                        // Refresh user data
                        $stmt = $pdo->prepare("SELECT u.*, r.name as role_name FROM users u JOIN roles r ON u.role_id = r.id WHERE u.id = ?");
                        $stmt->execute([$user_id]);
                        $user_data = $stmt->fetch();
                        // Refresh company info
                        $stmt = $pdo->prepare("SELECT * FROM companies WHERE user_id = ?");
                        $stmt->execute([$user_id]);
                        $company_info = $stmt->fetch();
                    } else {
                        $error = 'No se pudo actualizar la empresa.';
                    }
                }
            }
        }
    }
}

$page_title = 'Editar Empresa - ' . htmlspecialchars($company_info['company_name'] ?? $user_data['first_name'] . ' ' . $user_data['last_name']);

$content = '<div class="row">
    <div class="col-md-8">
        <div class="card card-primary">
            <div class="card-header">
                <h3 class="card-title">Editar Empresa</h3>
            </div>
            <form method="post" enctype="multipart/form-data">
                <input type="hidden" name="csrf_token" value="' . get_csrf_token() . '">
                <div class="card-body">' .
                    ($error ? '<div class="alert alert-danger">' . $error . '</div>' : '') .
                    ($success ? '<div class="alert alert-success">' . $success . '</div>' : '') .
                    '<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" value="' . htmlspecialchars($user_data['username']) . '" required>
                            </div>
                            <div class="form-group">
                                <label for="email">Correo Electrónico *</label>
                                <input type="email" class="form-control" id="email" name="email" value="' . htmlspecialchars($user_data['email']) . '" required>
                            </div>
                            <div class="form-group">
                                <label for="first_name">Nombres del Contacto</label>
                                <input type="text" class="form-control" id="first_name" name="first_name" value="' . htmlspecialchars($user_data['first_name']) . '">
                            </div>
                            <div class="form-group">
                                <label for="last_name">Apellidos del Contacto</label>
                                <input type="text" class="form-control" id="last_name" name="last_name" value="' . htmlspecialchars($user_data['last_name']) . '">
                            </div>
                            <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">Dejar vacío para mantener la foto actual. Máx 2MB, JPG/PNG/GIF.</small>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <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" value="' . htmlspecialchars($company_info['company_name']) . '" required>
                                <small class="form-text text-muted">Nombre oficial de la empresa</small>
                            </div>
                            <div class="form-group">
                                <label for="phone">Teléfono</label>
                                <input type="tel" class="form-control" id="phone" name="phone" value="' . htmlspecialchars($company_info['phone'] ?? '') . '" placeholder="Número de teléfono">
                            </div>
                            <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">Dejar vacío para mantener el logo actual. Máx 2MB, JPG/PNG/GIF.</small>
                            </div>
                            <div class="form-group">
                                <label for="address">Dirección</label>
                                <input type="text" class="form-control" id="address" name="address" value="' . htmlspecialchars($company_info['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" value="' . htmlspecialchars($company_info['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="3" placeholder="Describe la empresa, su misión, visión, productos/servicios, etc.">' . htmlspecialchars($company_info['description'] ?? '') . '</textarea>
                                <small class="form-text text-muted">Describe la empresa y sus actividades</small>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="card-footer">
                    <button type="submit" class="btn btn-primary">Actualizar Empresa</button>
                    <a href="' . url('admin/companies') . '" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Volver</a>
                </div>
            </form>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Foto actual del contacto</h3>
            </div>
            <div class="card-body text-center">' .
                ((isset($user_data['photo']) && !empty($user_data['photo']) && file_exists(BASE_PATH . '/' . $user_data['photo'])) ? '<img src="' . url($user_data['photo']) . '" class="img-fluid rounded-circle" style="max-height: 120px; max-width: 120px; object-fit: cover;" alt="Current Photo">' : '<div class="text-muted"><i class="fas fa-user fa-3x mb-2"></i><br>No hay foto actual</div>') .
            '</div>
        </div>
        <div class="card mt-3">
            <div class="card-header">
                <h3 class="card-title">Logo actual de la empresa</h3>
            </div>
            <div class="card-body text-center">' .
                ((isset($company_info['logo']) && !empty($company_info['logo']) && file_exists(BASE_PATH . '/' . $company_info['logo'])) ? '<img src="' . url($company_info['logo']) . '" class="img-fluid" style="max-height: 120px;" alt="Current Logo">' : '<div class="text-muted"><i class="fas fa-building fa-3x mb-2"></i><br>No hay logo actual</div>') .
            '</div>
        </div>
    </div>
</div>';

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