<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Database;

class ProfileController extends Controller
{
    private function requireLogin()
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        if (empty($_SESSION['user_id'])) {

            header("Location: /easychair/login");

            exit;
        }
    }

    /*
    --------------------------------------------------
    PROFILE PAGE
    --------------------------------------------------
    */

public function index()
{
    $this->requireLogin();

    $db = Database::getInstance();

    $userId =
        (int)($_SESSION['user_id'] ?? 0);

    $conferenceId =
        (int)($_SESSION['conference_id'] ?? 0);

    /*
    ------------------------------------------------
    USER
    ------------------------------------------------
    */

    $stmt = $db->prepare("
        SELECT *
        FROM users
        WHERE id = ?
        LIMIT 1
    ");

    $stmt->execute([$userId]);

    $user =
        $stmt->fetch(\PDO::FETCH_ASSOC);

    if (!$user) {
        die('User not found.');
    }

    /*
    ------------------------------------------------
    PROFILE
    ------------------------------------------------
    */

    $profile = [];

    try {

        $stmt = $db->prepare("
            SELECT *
            FROM user_profiles
            WHERE user_id = ?
            LIMIT 1
        ");

        $stmt->execute([$userId]);

        $profile =
            $stmt->fetch(\PDO::FETCH_ASSOC) ?: [];

    } catch (\Throwable $e) {}

    /*
    ------------------------------------------------
    CONFERENCE
    ------------------------------------------------
    */

    $conference = [];

    if ($conferenceId > 0) {

        try {

            $stmt = $db->prepare("
                SELECT *
                FROM conferences
                WHERE id = ?
                LIMIT 1
            ");

            $stmt->execute([$conferenceId]);

            $conference =
                $stmt->fetch(\PDO::FETCH_ASSOC) ?: [];

        } catch (\Throwable $e) {}
    }

    /*
    ------------------------------------------------
    PROFILE FIELD RULES
    ------------------------------------------------
    */

    $fieldRules = [];

    try {

        $stmt = $db->prepare("
            SELECT *
            FROM profile_field_rules
            WHERE conference_id = ?
            AND is_active = 1
        ");

        $stmt->execute([$conferenceId]);

        foreach (
            $stmt->fetchAll(\PDO::FETCH_ASSOC)
            as $r
        ) {

            $fieldRules[
                $r['field_key']
            ] = $r;
        }

    } catch (\Throwable $e) {}

    /*
    ------------------------------------------------
    CUSTOM FIELDS
    ------------------------------------------------
    */

    $customFields = [];

    try {

        $stmt = $db->prepare("
            SELECT *
            FROM conference_profile_fields
            WHERE conference_id = ?
            AND is_active = 1
            ORDER BY sort_order ASC, id ASC
        ");

        $stmt->execute([$conferenceId]);

        $customFields =
            $stmt->fetchAll(\PDO::FETCH_ASSOC);

    } catch (\Throwable $e) {}

    /*
    ------------------------------------------------
    CUSTOM VALUES
    ------------------------------------------------
    */

    $customValues = [];

    try {

        $stmt = $db->prepare("
            SELECT
                field_id,
                field_value
            FROM user_profile_custom_values
            WHERE user_id = ?
            AND conference_id = ?
        ");

        $stmt->execute([
            $userId,
            $conferenceId
        ]);

        foreach (
            $stmt->fetchAll(\PDO::FETCH_ASSOC)
            as $v
        ) {

            $customValues[
                (int)$v['field_id']
            ] = $v['field_value'];
        }

    } catch (\Throwable $e) {}

    /*
    ------------------------------------------------
    MISSING REQUIRED FIELDS
    ------------------------------------------------
    */

    $missingFields = [];

    foreach ($fieldRules as $k => $r) {

        if (
            !empty($r['is_required'])
            &&
            empty($profile[$k])
        ) {

            $missingFields[] =
                $r['field_label']
                ?? $k;
        }
    }

    /*
    ------------------------------------------------
    ROLE
    ------------------------------------------------
    */

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

    $viewData = [

        'title' => 'My Profile',

        'user' => $user,
        'profile' => $profile,
        'conference' => $conference,

        'fieldRules' => $fieldRules,

        'customFields' => $customFields,
        'customValues' => $customValues,

        'missingFields' => $missingFields,

        'roleCode' => $role
    ];

    /*
    ------------------------------------------------
    ROLE LAYOUTS
    ------------------------------------------------
    */

    if (
        in_array(
            $role,
            [
                'super_admin',
                'org_admin',
                'conference_chair',
                'organizer',
                'track_chair',
                'section_editor',
                'admin'
            ],
            true
        )
    ) {

        $this->renderAdmin(
            'profile/index',
            $viewData
        );

        return;
    }

   
if ($role === 'reviewer') {

    extract($viewData);

    ob_start();

    require BASE_PATH . '/app/views/profile/index.php';

    $content = ob_get_clean();

    require BASE_PATH . '/app/views/layouts/reviewer_layout.php';

    return;
}



    $this->render(
        'profile/index',
        $viewData
    );
}

    /*
    --------------------------------------------------
    UPDATE PROFILE
    --------------------------------------------------
    */

    public function update()
    {
        $this->requireLogin();

        $db = Database::getInstance();

        $name =
            trim($_POST['name'] ?? '');

        $email =
            trim($_POST['email'] ?? '');

        if (!$name || !$email) {

            $_SESSION['error'] =
                "Name and Email are required.";

            header(
                "Location: /easychair/profile"
            );

            exit;
        }

        $stmt = $db->prepare("
            UPDATE users
            SET
                name = ?,
                email = ?,
                updated_at = NOW()
            WHERE id = ?
        ");

        $stmt->execute([

            $name,
            $email,
            (int)$_SESSION['user_id']

        ]);

        $_SESSION['success'] =
            "Profile updated successfully.";

        header(
            "Location: /easychair/profile"
        );

        exit;
    }


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

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {

        header('Location: /easychair/profile');
        exit;
    }

    $db = Database::getInstance();

    $userId =
        (int)($_SESSION['user_id'] ?? 0);

    $conferenceId =
        (int)($_SESSION['conference_id'] ?? 0);

    /*
    ------------------------------------------------
    BASIC USER FIELDS
    ------------------------------------------------
    */

    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');

    try {

        $stmt = $db->prepare("
            UPDATE users
            SET
                name = ?,
                email = ?,
                phone = ?
            WHERE id = ?
        ");

        $stmt->execute([
            $name,
            $email,
            $phone,
            $userId
        ]);

    } catch (\Throwable $e) {

        error_log(
            'PROFILE USER UPDATE ERROR: ' .
            $e->getMessage()
        );
    }

    /*
    ------------------------------------------------
    PROFILE TABLE
    ------------------------------------------------
    */

    $affiliation =
        trim($_POST['affiliation'] ?? '');

    $country =
        trim($_POST['country'] ?? '');

    $bio =
        trim($_POST['bio'] ?? '');

    try {

        $stmt = $db->prepare("
            SELECT id
            FROM user_profiles
            WHERE user_id = ?
            LIMIT 1
        ");

        $stmt->execute([$userId]);

        $exists =
            (int)$stmt->fetchColumn();

        if ($exists) {

            $stmt = $db->prepare("
                UPDATE user_profiles
                SET
                    affiliation = ?,
                    country = ?,
                    bio = ?,
                    updated_at = NOW()
                WHERE user_id = ?
            ");

            $stmt->execute([
                $affiliation,
                $country,
                $bio,
                $userId
            ]);

        } else {

            $stmt = $db->prepare("
                INSERT INTO user_profiles
                (
                    user_id,
                    affiliation,
                    country,
                    bio,
                    created_at,
                    updated_at
                )
                VALUES
                (
                    ?,
                    ?,
                    ?,
                    ?,
                    NOW(),
                    NOW()
                )
            ");

            $stmt->execute([
                $userId,
                $affiliation,
                $country,
                $bio
            ]);
        }

    } catch (\Throwable $e) {

        error_log(
            'PROFILE TABLE ERROR: ' .
            $e->getMessage()
        );
    }

    /*
    ------------------------------------------------
    CUSTOM PROFILE FIELDS
    ------------------------------------------------
    */

    if (!empty($_POST['custom_fields'])) {

        foreach ($_POST['custom_fields'] as $fieldId => $value) {

            $fieldId = (int)$fieldId;

            try {

                $stmt = $db->prepare("
                    SELECT id
                    FROM user_profile_custom_values
                    WHERE user_id = ?
                    AND conference_id = ?
                    AND field_id = ?
                    LIMIT 1
                ");

                $stmt->execute([
                    $userId,
                    $conferenceId,
                    $fieldId
                ]);

                $exists =
                    (int)$stmt->fetchColumn();

                if ($exists) {

                    $stmt = $db->prepare("
                        UPDATE user_profile_custom_values
                        SET
                            field_value = ?,
                            updated_at = NOW()
                        WHERE user_id = ?
                        AND conference_id = ?
                        AND field_id = ?
                    ");

                    $stmt->execute([
                        $value,
                        $userId,
                        $conferenceId,
                        $fieldId
                    ]);

                } else {

                    $stmt = $db->prepare("
                        INSERT INTO user_profile_custom_values
                        (
                            user_id,
                            conference_id,
                            field_id,
                            field_value,
                            created_at,
                            updated_at
                        )
                        VALUES
                        (
                            ?,
                            ?,
                            ?,
                            ?,
                            NOW(),
                            NOW()
                        )
                    ");

                    $stmt->execute([
                        $userId,
                        $conferenceId,
                        $fieldId,
                        $value
                    ]);
                }

            } catch (\Throwable $e) {

                error_log(
                    'PROFILE CUSTOM FIELD ERROR: ' .
                    $e->getMessage()
                );
            }
        }
    }

    $_SESSION['profile_success'] = 1;

    header('Location: /easychair/profile');
    exit;
}




}
