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

check_role('empresa');

$user = get_logged_in_user();

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

if (!$company) {
    die('Company profile not found.');
}

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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    $email = trim($_POST['email']);
    $company_name = trim($_POST['company_name']);
    $description = trim($_POST['description']);
    $website = trim($_POST['website']);
    $phone = trim($_POST['phone']);
    $address = trim($_POST['address']);

    if (empty($first_name) || empty($last_name) || empty($email) || empty($company_name)) {
        $error = 'Please fill in all required fields.';
    } else {
        // Check if email exists (excluding current user)
        $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
        $stmt->execute([$email, $user['id']]);
        if ($stmt->fetch()) {
            $error = 'Email already exists.';
        } else {
            // Handle logo upload
            $logo_path = $company['logo'];
            if (isset($_FILES['logo']) && $_FILES['logo']['error'] == 0) {
                $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
                if (in_array($_FILES['logo']['type'], $allowed_types) && $_FILES['logo']['size'] <= 2097152) { // 2MB
                    $upload_dir = '../uploads/logos/';
                    if (!is_dir($upload_dir)) {
                        if (!mkdir($upload_dir, 0755, true)) {
                            $error = 'Failed to create upload directory.';
                        }
                    }

                    if (!$error && is_writable($upload_dir)) {
                        $file_extension = 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('../' . $logo_path)) {
                                unlink('../' . $logo_path);
                            }
                            $logo_path = 'uploads/logos/' . $file_name;
                        } else {
                            $error = 'No se pudo cargar el archivo del logotipo.';
                        }
                    } else {
                        $error = 'El directorio de carga no se puede escribir.';
                    }
                } else {
                    $error = 'Tipo de archivo no válido o demasiado grande. Solo se permiten archivos JPG, PNG y GIF de menos de 2 MB';
                }
            }

            // Update user
            $stmt = $pdo->prepare("UPDATE users SET first_name = ?, last_name = ?, email = ? WHERE id = ?");
            $stmt->execute([$first_name, $last_name, $email, $user['id']]);

            // Update company
            $stmt = $pdo->prepare("UPDATE companies SET company_name = ?, description = ?, website = ?, phone = ?, address = ?, logo = ? WHERE user_id = ?");
            if ($stmt->execute([$company_name, $description, $website, $phone, $address, $logo_path, $user['id']])) {
                $success = 'Perfil actualizado exitosamente.';
                // Refresh data
                $user = get_logged_in_user();
                $stmt = $pdo->prepare("SELECT * FROM companies WHERE user_id = ?");
                $stmt->execute([$user['id']]);
                $company = $stmt->fetch();
            } else {
                $error = 'No se pudo actualizar el perfil.';
            }
        }
    }
}

// Get company statistics
$stats = [];
$stmt = $pdo->prepare("SELECT COUNT(*) as total_jobs FROM jobs WHERE company_id = ?");
$stmt->execute([$company['id']]);
$stats['total_jobs'] = $stmt->fetch()['total_jobs'];

$stmt = $pdo->prepare("SELECT COUNT(*) as active_jobs FROM jobs WHERE company_id = ? AND status = 'active'");
$stmt->execute([$company['id']]);
$stats['active_jobs'] = $stmt->fetch()['active_jobs'];

$stmt = $pdo->prepare("SELECT COUNT(a.id) as total_applications FROM applications a JOIN jobs j ON a.job_id = j.id WHERE j.company_id = ?");
$stmt->execute([$company['id']]);
$stats['total_applications'] = $stmt->fetch()['total_applications'];

$page_title = 'Perfil de la Empresa';

$content = '
<div class="row">
    <div class="col-md-4">
        <div class="card card-primary card-outline">
            <div class="card-body box-profile">
                <div class="text-center">
                    ' . ($company['logo'] ? '<img class="profile-user-img img-fluid img-circle" src="../' . htmlspecialchars($company['logo']) . '" alt="Company Logo" style="width: 100px; height: 100px; object-fit: cover;">' : '<div class="profile-user-img img-fluid img-circle bg-light d-flex align-items-center justify-content-center" style="width: 100px; height: 100px;"><i class="fas fa-building fa-2x text-muted"></i></div>') . '
                </div>
                <h3 class="profile-username text-center">' . htmlspecialchars($company['company_name']) . '</h3>
                <p class="text-muted text-center">Empresa</p>
                <ul class="list-group list-group-unbordered mb-3">
                    <li class="list-group-item">
                        <b>Contacto</b> <a class="float-right">' . htmlspecialchars($user['first_name'] . ' ' . $user['last_name']) . '</a>
                    </li>
                    <li class="list-group-item">
                        <b>Email</b> <a class="float-right">' . htmlspecialchars($user['email']) . '</a>
                    </li>
                    <li class="list-group-item">
                        <b>Registro</b> <a class="float-right">' . date('d M, Y', strtotime($company['created_at'])) . '</a>
                    </li>
                </ul>
                <div class="text-center">
                    
                </div>
            </div>
        </div>
        <p></p> 
        <!-- Statistics Card -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Estadísticas</h3>
            </div>
            <div class="card-body">
                <div class="row text-center">
                    <div class="col-6">
                        <div class="small-box bg-info">
                            <div class="inner">
                                <h3>' . $stats['total_jobs'] . '</h3>
                                <p>Total </p>
                            </div>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="small-box bg-success">
                            <div class="inner">
                                <h3>' . $stats['active_jobs'] . '</h3>
                                <p>Activos</p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row text-center mt-2">
                    <div class="col-12">
                        <div class="small-box bg-warning">
                            <div class="inner">
                                <h3>' . $stats['total_applications'] . '</h3>
                                <p>Postulantes</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-md-8">
        <div class="card card-primary">
            <div class="card-header">
                <h3 class="card-title">Editar</h3>
            </div>
            <form method="post" enctype="multipart/form-data">
                <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">
                            <h5>Información de Contacto</h5>
                            <div class="form-group">
                                <label for="first_name">First Name *</label>
                                <input type="text" class="form-control" id="first_name" name="first_name" value="' . htmlspecialchars($user['first_name']) . '" required>
                            </div>
                            <div class="form-group">
                                <label for="last_name">Nombre Completo *</label>
                                <input type="text" class="form-control" id="last_name" name="last_name" value="' . htmlspecialchars($user['last_name']) . '" required>
                            </div>
                            <div class="form-group">
                                <label for="email">Email *</label>
                                <input type="email" class="form-control" id="email" name="email" value="' . htmlspecialchars($user['email']) . '" required>
                            </div>
                            <div class="form-group">
                                <label for="phone">Celular</label>
                                <input type="tel" class="form-control" id="phone" name="phone" value="' . htmlspecialchars($company['phone'] ?? '') . '">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <h5>Información de Empresa</h5>
                            <div class="form-group">
                                <label for="company_name">Razon Social *</label>
                                <input type="text" class="form-control" id="company_name" name="company_name" value="' . htmlspecialchars($company['company_name']) . '" required>
                            </div>
                            <div class="form-group">
                                <label for="website">Website</label>
                                <input type="url" class="form-control" id="website" name="website" value="' . htmlspecialchars($company['website'] ?? '') . '" placeholder="https://example.com">
                            </div>
                            <div class="form-group">
                                <label for="logo">Logo</label>
                                <input type="file" class="form-control" id="logo" name="logo" accept="image/*">
                                <small class="form-text text-muted">Déjelo en blanco para mantener el logotipo actual. Máximo 2 MB, solo JPG/PNG/GIF.</small>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-12">
                            <div class="form-group">
                                <label for="address">Dirección</label>
                                <textarea class="form-control" id="address" name="address" rows="2">' . htmlspecialchars($company['address'] ?? '') . '</textarea>
                            </div>
                            <div class="form-group">
                                <label for="description">Descripción</label>
                                <textarea class="form-control" id="description" name="description" rows="4" placeholder="Tell us about your company...">' . htmlspecialchars($company['description'] ?? '') . '</textarea>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="card-footer">
                    <button type="submit" class="btn btn-primary">Actualizar</button>
                </div>
            </form>
        </div>
    </div>
</div>';

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