<?php
namespace App\Services;

use App\Core\Database;
use App\Services\ConferenceEmailTemplateService;
use App\Services\WorkflowDictionary;

class SubmissionWorkflowService
{
    public static function log(
        int $submissionId,
        string $eventKey,
        string $title,
        string $body = '',
        ?int $actorId = null,
        ?string $actorRole = null
    ): void {
        $db = Database::getInstance();

        $stmt = $db->prepare("
            SELECT org_id, conference_id
            FROM submissions
            WHERE id = ?
            LIMIT 1
        ");
        $stmt->execute([$submissionId]);
        $s = $stmt->fetch(\PDO::FETCH_ASSOC);

        if (!$s) {
            return;
        }

        $stmt = $db->prepare("
            INSERT INTO submission_activity_log
            (org_id, conference_id, submission_id, actor_id, actor_role, event_key, event_title, event_body)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ");

        $stmt->execute([
            (int)$s['org_id'],
            (int)$s['conference_id'],
            $submissionId,
            $actorId,
            $actorRole,
            $eventKey,
            $title,
            $body
        ]);
    }

    public static function addVersion(
        int $submissionId,
        string $filePath,
        string $originalFilename,
        int $uploadedBy,
        string $uploadType = 'revision',
        string $note = ''
    ): void {
        $db = Database::getInstance();

        $stmt = $db->prepare("
            SELECT org_id, conference_id, COALESCE(MAX(current_version),1) AS current_version
            FROM submissions
            WHERE id = ?
            GROUP BY org_id, conference_id
            LIMIT 1
        ");
        $stmt->execute([$submissionId]);
        $s = $stmt->fetch(\PDO::FETCH_ASSOC);

        if (!$s) {
            return;
        }

        $versionNo = (int)$s['current_version'] + 1;

        $stmt = $db->prepare("
            INSERT INTO submission_versions
            (org_id, conference_id, submission_id, version_no, file_path, original_filename, uploaded_by, upload_type, note)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");

        $stmt->execute([
            (int)$s['org_id'],
            (int)$s['conference_id'],
            $submissionId,
            $versionNo,
            $filePath,
            $originalFilename,
            $uploadedBy,
            $uploadType,
            $note
        ]);

        $stmt = $db->prepare("
            UPDATE submissions
            SET current_version = ?,
                revision_file = ?,
                status = 'revised',
                stage = 'review',
                updated_by = ?,
                updated_at = NOW()
            WHERE id = ?
        ");
        $stmt->execute([$versionNo, $filePath, $uploadedBy, $submissionId]);

        self::log(
            $submissionId,
            'revision_uploaded',
            'Revision uploaded',
            'A new revision file was uploaded.',
            $uploadedBy,
            $_SESSION['role'] ?? null
        );
    }

    public static function queueEmail(
        int $conferenceId,
        string $templateKey,
        string $recipientEmail,
        string $recipientName,
        array $vars = [],
        ?int $submissionId = null,
        ?int $userId = null,
        string $lang = 'en'
    ): void {
        if (!class_exists(ConferenceEmailTemplateService::class)) {
            return;
        }

        $db = Database::getInstance();

        $stmt = $db->prepare("
            SELECT org_id
            FROM conferences
            WHERE id = ?
            LIMIT 1
        ");
        $stmt->execute([$conferenceId]);
        $orgId = (int)$stmt->fetchColumn();

        /* PACK818E
--------------------------------------------------
Reviewer + Track Chair Credentials
--------------------------------------------------
*/

$emailTarget = null;
$passwordVar = null;
$prefix      = null;

if (
    empty($vars['reviewer_password'])
    &&
    !empty($vars['reviewer_email'])
) {

    $emailTarget =
        $vars['reviewer_email'];

    $passwordVar =
        'reviewer_password';

    $prefix =
        'RV-';

}
elseif (
    empty($vars['track_chair_password'])
    &&
    !empty($vars['track_chair_email'])
) {

    $emailTarget =
        $vars['track_chair_email'];

    $passwordVar =
        'track_chair_password';

    $prefix =
        'TC-';

}

if ($emailTarget) {

    $tempPassword =
        $prefix .
        random_int(
            100000,
            999999
        );

    $stmtTmp = $db->prepare("
        UPDATE users
        SET
            password_hash=?,
            must_change_password=1,
            updated_at=NOW()
        WHERE email=?
    ");

    $stmtTmp->execute([

        password_hash(
            $tempPassword,
            PASSWORD_DEFAULT
        ),

        $emailTarget

    ]);

    $vars[$passwordVar] =
        $tempPassword;
}

$rendered = ConferenceEmailTemplateService::render(
$conferenceId,
$templateKey,
$vars,
$lang
);


        if (empty($rendered['subject']) && empty($rendered['body'])) {
            return;
        }

        $stmt = $db->prepare("
            INSERT INTO conference_mail_outbox
            (org_id, conference_id, submission_id, user_id, template_key, recipient_email, recipient_name, subject, body, created_by)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");

        $stmt->execute([
            $orgId ?: null,
            $conferenceId,
            $submissionId,
            $userId,
            $templateKey,
            $recipientEmail,
            $recipientName,
            $rendered['subject'],
            $rendered['body'],
            $_SESSION['user_id'] ?? null
        ]);
    }

    
public static function submissionVars(
array $submission,
array $conference=[],
array $reviewer=[]
): array {

$confId=
(int)(
$conference['id']
??
0
);

$slug=
(string)(
$conference['slug']
??
''
);

$base=
'https://www.jpu.edu.jo/easychair';

$submissionDate=
$submission['submitted_at']
??
$submission['created_at']
??
date('Y-m-d H:i:s');

$due=
date(
'd/m/Y',
strtotime(
$submissionDate
.' +14 days'
)
);

$logo=
$conference['logo_path']
??
'';

if(
$logo
&&
strpos($logo,'http')!==0
){

$logo=
$base
.'/'
.ltrim($logo,'/');

}



$base='https://www.jpu.edu.jo/easychair';

$slug=
(string)(
$conference['slug']
??
''
);

$submissionDate=
$submission['submitted_at']
??
$submission['created_at']
??
date('Y-m-d H:i:s');

$dueDate=
date(
'd/m/Y',
strtotime(
$submissionDate
.' +14 days'
)
);

$logo=
$conference['logo_path']
??
'';

if(
$logo
&&
strpos($logo,'http')!==0
){

$logo=
$base
.'/'
.ltrim($logo,'/');

}

return [

'conference_title'=>
(
$conference['title_en']
??
$conference['title_ar']
??
''
),

'conference_short_name'=>
(
$conference['short_name']
??
''
),

'conference_slug'=>
$slug,

'conference_logo'=>
$logo,

'conference_logo'=>$logo,
'conference_slug'=>$slug,
'conference_url'=>$base.'/conference/'.$slug,

'conference_url_old'=>
$base
.'/conference/'
.$slug,

'title_en'=>
(
$submission['title_en']
??
''
),

'title_ar'=>
(
$submission['title_ar']
??
''
),

'abstract'=>
(
$submission['abstract']
??
$submission['abstract_en']
??
$submission['abstract_ar']
??
''
),

'paper_id'=>
(
$submission['id']
??
''
),

'submission_no'=>
(
$submission['submission_no']
??
$submission['id']
??
''
),

'category'=>
(
$submission['category']
??
$submission['track_name']
??
''
),

'status'=>
(
$submission['status']
??
''
),

'keywords'=>
(
$submission['keywords']
??
''
),

'reviewer_name'=>
trim(
($reviewer['first_name']??'')
.' '.
($reviewer['last_name']??'')
),

'reviewer_email'=>
(
$reviewer['email']
??
''
),

'submission_link'=>$base.'/submission/'.($submission['id']??0),

'submission_link_old'=>
$base
.'/submission/'
.
(
$submission['id']
??
0
),

'review_link'=>$base.'/reviewer/review?id='.($submission['id']??0),

'review_link_old'=>
$base
.'/reviewer/review?id='
.
(
$submission['id']
??
0
),

'due_date'=>
$due

];

}


/* ============================================================
   REVIEWER ASSIGNED
============================================================ */

public static function onReviewerAssigned(
    int $submissionId,
    ?int $actorId = null
): void {

    $db = Database::getInstance();

    $stmt = $db->prepare("
        UPDATE submissions
        SET
            status = 'under_review',
            stage = 'review',
            updated_by = ?,
            updated_at = NOW()
        WHERE id = ?
           ");

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

    self::log(
        $submissionId,
        'reviewer_assigned',
        'Reviewer assigned',
        'Submission entered review stage.',
        $actorId,
        $_SESSION['role'] ?? null
    );
}

/* ============================================================
   REVIEW COMPLETED
============================================================ */

public static function onReviewCompleted(
    int $submissionId,
    ?int $actorId = null
): void {

    $db = Database::getInstance();

    /*
    -----------------------------------------
    Count assignments
    -----------------------------------------
    */

    $stmt = $db->prepare("
        SELECT
            COUNT(*) AS total_reviews,

            SUM(
                CASE
                    WHEN status = 'completed'
                    THEN 1
                    ELSE 0
                END
            ) AS completed_reviews

        FROM review_assignments

        WHERE submission_id = ?
    ");

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

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

    $total =
        (int)($stats['total_reviews'] ?? 0);

    $completed =
        (int)($stats['completed_reviews'] ?? 0);

    /*
    -----------------------------------------
    ALL REVIEWS COMPLETE
    -----------------------------------------
    */

    if (
        $total > 0
        &&
        $completed >= $total
    ) {

/*
-----------------------------------------
AUTO CALCULATE AVG SCORE
-----------------------------------------
*/

$stmtAvg = $db->prepare("
    SELECT
        AVG(overall_score) AS avg_score
    FROM reviews
    WHERE submission_id = ?
");

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

$avgScore =
    (float)(
        $stmtAvg->fetchColumn()
        ?: 0
    );

/*
-----------------------------------------
AUTO DETERMINE RECOMMENDATION
-----------------------------------------
*/

$recommendedDecision = 'reject';

if ($avgScore >= 85) {

    $recommendedDecision = 'accept';

} elseif ($avgScore >= 70) {

    $recommendedDecision = 'minor_revision';

} elseif ($avgScore >= 50) {

    $recommendedDecision = 'major_revision';
}

$stmt = $db->prepare("
UPDATE submissions
SET
    status = 'under_review',
    stage = 'decision',

    workflow_stage = 'decision',
    workflow_updated_at = NOW(),

    avg_score = ?,
    recommended_decision = ?,

    updated_by = ?,
    updated_at = NOW()

WHERE id = ?
");

$stmt->execute([

    $avgScore,
    $recommendedDecision,

    $actorId,
    $submissionId
]);
self::log(
    $submissionId,
    'review_recommendation_ready',
    'Review recommendation generated',
    'Average score: '
    . number_format($avgScore, 2)
    . ' | Recommendation: '
    . $recommendedDecision,
    $actorId,
    $_SESSION['role'] ?? null
);   

 }
}

/* ============================================================
   CAMERA READY UPLOADED
============================================================ */

public static function onCameraReadyUploaded(
    int $submissionId,
    ?int $actorId = null
): void {

    $db = Database::getInstance();

    $stmt = $db->prepare("
        UPDATE submissions
        SET
            status = 'production',
            stage = 'production',
            updated_by = ?,
            updated_at = NOW()
        WHERE id = ?
    ");

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

    self::log(
        $submissionId,
        'camera_ready_uploaded',
        'Camera-ready uploaded',
        'Submission moved to production.',
        $actorId,
        $_SESSION['role'] ?? null
    );
}



}
