<?php
namespace App\Controllers;

use App\Core\Database;

class AuthorProfileController
{
    protected function db()
    {
        return Database::getInstance();
    }

    private function startSession(): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }
    }

    private function requireAuthor(): void
    {
        $this->startSession();

        if (empty($_SESSION['user_id'])) {
            header("Location: /easychair/login");
            exit;
        }

        $role = $_SESSION['conference_role'] ?? $_SESSION['role'] ?? $_SESSION['user_role'] ?? '';

        if ($role !== 'author') {
            http_response_code(403);
            exit("Author access required.");
        }
    }

    public function complete()
    {
        $this->requireAuthor();

        $stmt = $this->db()->prepare("
            SELECT id, first_name, last_name, email, phone, mobile
            FROM users
            WHERE id = ?
            LIMIT 1
        ");
        $stmt->execute([(int)$_SESSION['user_id']]);
        $user = $stmt->fetch(\PDO::FETCH_ASSOC);

        if (!$user) {
            exit("User not found.");
        }

        ob_start();
        require BASE_PATH . '/app/views/author/profile_required.php';
        $content = ob_get_clean();

        require BASE_PATH . '/app/views/layouts/author_layout.php';
    }

    public function save()
    {
        $this->requireAuthor();

        $phone = trim($_POST['phone'] ?? '');
        $firstName = trim($_POST['first_name'] ?? '');
        $lastName = trim($_POST['last_name'] ?? '');

        if ($phone === '') {
            $_SESSION['error'] = "Phone is compulsory.";
            header("Location: /easychair/author/profile/complete");
            exit;
        }

        $stmt = $this->db()->prepare("
            UPDATE users
            SET first_name = COALESCE(NULLIF(?,''), first_name),
                last_name = COALESCE(NULLIF(?,''), last_name),
                phone = ?,
                mobile = COALESCE(NULLIF(mobile,''), ?)
            WHERE id = ?
        ");
        $stmt->execute([
            $firstName,
            $lastName,
            $phone,
            $phone,
            (int)$_SESSION['user_id']
        ]);

        $_SESSION['user_name'] = trim($firstName . ' ' . $lastName) ?: ($_SESSION['user_name'] ?? '');

        header("Location: /easychair/author/dashboard");
        exit;
    }
}
