<?php

namespace App\Controllers;

require_once BASE_PATH . '/app/helpers/permissions.php';

use App\Core\Database;

class ProductionController
{
    private function requireAccess()
    {
        if (!isset($_SESSION['user_id'])) {

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

        }

        $allowed = [

            'organizer',
            'org_admin',
            'superadmin'

        ];

        if (!in_array(
            $_SESSION['role_code'] ?? '',
            $allowed
        )) {

            http_response_code(403);

            die("Access denied.");

        }
    }

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

        $db =
            Database::getInstance();

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

        $stmt =
            $db->prepare("
                SELECT
                    id,
                    title,
                    stage,
                    status
                FROM submissions
                WHERE conference_id = ?
                AND stage IN (
                    'proofreading',
                    'production',
                    'galley',
                    'assigned_to_issue'
                )
                ORDER BY id DESC
            ");

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

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

        require
            BASE_PATH .
            '/app/views/production/index.php';
    }

public function uploadFile()
{
    $this->requireAccess();

    $db =
        Database::getInstance();

    $submissionId =
        (int)($_POST['submission_id'] ?? 0);

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

    if (!$submissionId || !$stage) {

        die("Invalid upload.");

    }

    $file =
        $_FILES['file'] ?? null;

    if (!$file
        || !is_uploaded_file(
            $file['tmp_name']
        )
    ) {

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

        exit;

    }

    $uploadDir =
        BASE_PATH .
        '/public/uploads/production/';

    if (!is_dir($uploadDir)) {

        mkdir(
            $uploadDir,
            0775,
            true
        );

    }

    $filename =
        'submission_' .
        $submissionId .
        '_' .
        time() .
        '.pdf';

    $relativePath =
        'uploads/production/' .
        $filename;

    move_uploaded_file(

        $file['tmp_name'],

        $uploadDir .
        $filename

    );

    /*
    Save file
    */

    $db->prepare("
        INSERT INTO submission_files
        (
            submission_id,
            file_category,
            file_path,
            uploaded_by,
            created_at
        )
        VALUES
        (?, ?, ?, ?, NOW())
    ")
    ->execute([

        $submissionId,
        $stage,
        $relativePath,
        $_SESSION['user_id']

    ]);

    /*
    Move workflow stage
    */

    $db->prepare("
        UPDATE submissions
        SET stage = ?
        WHERE id = ?
    ")
    ->execute([

        $stage,
        $submissionId

    ]);

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

    exit;
}

public function assignIssue()
{
    $this->requireAccess();

    $db =
        Database::getInstance();

    $submissionId =
        (int)$_POST['submission_id'];

    $issueId =
        (int)$_POST['issue_id'];

    $db->prepare("
        UPDATE submissions
        SET
            issue_id = ?,
            stage = 'assigned_to_issue'
        WHERE id = ?
    ")
    ->execute([

        $issueId,
        $submissionId

    ]);

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

    exit;
}


public function publish()
{
    $this->requireAccess();

    $db =
        Database::getInstance();

    $submissionId =
        (int)$_POST['submission_id'];

    /*
    Resolve conference
    */

    $stmt =
        $db->prepare("
            SELECT conference_id
            FROM submissions
            WHERE id = ?
        ");

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

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

    /*
    Generate DOI
    */

    $doi =
        \App\Services\DoiService::generate(

            $submissionId,
            $conferenceId

        );

    /*
    Publish submission
    */

    $db->prepare("
        UPDATE submissions
        SET
            stage = 'published',
            status = 'published',
            published_at = NOW(),
            doi = ?
        WHERE id = ?
    ")
    ->execute([

        $doi,
        $submissionId

    ]);

    error_log(
        "PUBLISHED WITH DOI: submission="
        . $submissionId .
        " doi=" .
        $doi
    );

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

    exit;
}



}
