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

check_role('administrador');

$user = get_logged_in_user();

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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    $email = trim($_POST['email']);
    $current_password = $_POST['current_password'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    if (empty($first_name) || empty($last_name) || empty($email)) {
        $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 password change
            $update_password = false;
            if (!empty($new_password)) {
                if (empty($current_password)) {
                    $error = 'Current password is required to change password.';
                } elseif (!password_verify($current_password, $user['password'])) {
                    $error = 'Current password is incorrect.';
                } elseif (strlen($new_password) < 6) {
                    $error = 'New password must be at least 6 characters long.';
                } elseif ($new_password !== $confirm_password) {
                    $error = 'New passwords do not match.';
                } else {
                    $update_password = true;
                }
            }

            if (!$error) {
                // Handle photo upload
                $photo_path = isset($user['photo']) ? $user['photo'] : '';
                if (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 = '../uploads/photos/';
                        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['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('../' . $photo_path)) {
                                    unlink('../' . $photo_path);
                                }
                                $photo_path = 'uploads/photos/' . $file_name;
                            } else {
                                $error = 'Failed to upload photo file.';
                            }
                        } else {
                            $error = 'Upload directory is not writable.';
                        }
                    } else {
                        $error = 'Invalid file type or file too large. Only JPG, PNG, GIF files under 2MB are allowed.';
                    }
                }

                if (!$error) {
                    // Update user
                    if ($update_password) {
                        $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                        $stmt = $pdo->prepare("UPDATE users SET first_name = ?, last_name = ?, email = ?, password = ?, photo = ? WHERE id = ?");
                        $stmt->execute([$first_name, $last_name, $email, $hashed_password, $photo_path, $user['id']]);
                    } else {
                        $stmt = $pdo->prepare("UPDATE users SET first_name = ?, last_name = ?, email = ?, photo = ? WHERE id = ?");
                        $stmt->execute([$first_name, $last_name, $email, $photo_path, $user['id']]);
                    }

                    $success = 'Profile updated successfully.';
                    // Refresh user data
                    $user = get_logged_in_user();
                }
            }
        }
    }
}


$page_title = 'Perfil Administrador';

$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">
                    <img class="profile-user-img img-fluid img-circle" src="' . ((isset($user['photo']) && $user['photo']) ? '../' . htmlspecialchars($user['photo']) : '../assets/img/avatar.png') . '" alt="Admin Photo">
                </div>
                <h3 class="profile-username text-center">' . htmlspecialchars($user['first_name'] . ' ' . $user['last_name']) . '</h3>
                <p class="text-muted text-center">System Administrator</p>
                <ul class="list-group list-group-unbordered mb-3">
                    <li class="list-group-item">
                        <b>Email</b> <a class="float-right">' . htmlspecialchars($user['email']) . '</a>
                    </li>
                    <li class="list-group-item">
                        <b>Username</b> <a class="float-right">' . htmlspecialchars($user['username']) . '</a>
                    </li>
                    <li class="list-group-item">
                        <b>Joined</b> <a class="float-right">' . date('M d, Y', strtotime($user['created_at'])) . '</a>
                    </li>
                </ul>
            </div>
        </div>

    </div>

    <div class="col-md-8">
        <div class="card card-primary">
            <div class="card-header">
                <h3 class="card-title">Editar Perfil Admin  </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 Perosnal</h5>
                            <div class="form-group">
                                <label for="first_name">Nombres *</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">Apellidos *</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="username">Username</label>
                                <input type="text" class="form-control" id="username" value="' . htmlspecialchars($user['username']) . '" readonly>
                                <small class="form-text text-muted">Username no se puede cambiar</small>
                            </div>
                            <div class="form-group">
                                <label for="photo">Foto de Perfil</label>
                                <input type="file" class="form-control" id="photo" name="photo" accept="image/*">
                                <small class="form-text text-muted">Dejalo en blanco para mantener la foto actual. Max 2MB, JPG/PNG/GIF only.</small>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <h5>Cambiar Contraseña</h5>
                            <div class="form-group">
                                <label for="current_password">Contarseña actual</label>
                                <input type="password" class="form-control" id="current_password" name="current_password">
                                <small class="form-text text-muted">Requerido sólo si se cambia la contraseña</small>
                            </div>
                            <div class="form-group">
                                <label for="new_password">Nueva contraseña</label>
                                <input type="password" class="form-control" id="new_password" name="new_password">
                                <small class="form-text text-muted">Dejar vacía para mantener la contraseña actual</small>
                            </div>
                            <div class="form-group">
                                <label for="confirm_password">Confirma Nueva contraseña</label>
                                <input type="password" class="form-control" id="confirm_password" name="confirm_password">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="card-footer">
                    <button type="submit" class="btn btn-primary">Update Profile</button>
                    <a href="dashboard.php" class="btn btn-secondary">Cancel</a>
                </div>
            </form>
        </div>

    </div>
</div>';

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