<?php
declare(strict_types=1);

use App\Core\Database;

return function (Database $db): void {
    $ts = date('Y-m-d H:i:s');

    $definitions = [
        // ── 1. Leave Approval Workflow ──
        [
            'workflow_code'  => 'hr_leave_approval',
            'name_ar'        => 'اعتماد الإجازات',
            'name_en'        => 'Leave Approval',
            'description_ar' => 'دورة عمل طلب واعتماد الإجازات للموظفين',
            'definition_json' => json_encode([
                'states' => [
                    'submitted'        => ['label_ar' => 'تم التقديم',          'label_en' => 'Submitted',         'type' => 'initial'],
                    'manager_review'   => ['label_ar' => 'مراجعة المدير',       'label_en' => 'Manager Review',    'type' => 'intermediate'],
                    'hr_review'        => ['label_ar' => 'مراجعة الموارد البشرية', 'label_en' => 'HR Review',      'type' => 'intermediate'],
                    'approved'         => ['label_ar' => 'معتمد',               'label_en' => 'Approved',          'type' => 'terminal'],
                    'rejected'         => ['label_ar' => 'مرفوض',               'label_en' => 'Rejected',          'type' => 'terminal'],
                    'cancelled'        => ['label_ar' => 'ملغى',                'label_en' => 'Cancelled',         'type' => 'terminal'],
                ],
                'transitions' => [
                    ['name' => 'submit_to_manager',  'from' => 'submitted',      'to' => 'manager_review',  'guards' => [['type' => 'permission', 'value' => 'hr.leave.request']],  'actions' => [['type' => 'event', 'value' => 'hr.leave.submitted']]],
                    ['name' => 'manager_approve',    'from' => 'manager_review', 'to' => 'hr_review',       'guards' => [['type' => 'permission', 'value' => 'hr.leave.approve']],  'actions' => [['type' => 'event', 'value' => 'hr.leave.manager_approved']]],
                    ['name' => 'manager_reject',     'from' => 'manager_review', 'to' => 'rejected',        'guards' => [['type' => 'permission', 'value' => 'hr.leave.approve']],  'actions' => [['type' => 'event', 'value' => 'hr.leave.rejected']]],
                    ['name' => 'hr_approve',          'from' => 'hr_review',     'to' => 'approved',        'guards' => [['type' => 'permission', 'value' => 'hr.leave.manage']],   'actions' => [['type' => 'event', 'value' => 'hr.leave.approved']]],
                    ['name' => 'hr_reject',            'from' => 'hr_review',    'to' => 'rejected',        'guards' => [['type' => 'permission', 'value' => 'hr.leave.manage']],   'actions' => [['type' => 'event', 'value' => 'hr.leave.rejected']]],
                    ['name' => 'cancel',               'from' => 'submitted',    'to' => 'cancelled',       'guards' => [['type' => 'condition', 'value' => 'is_requester']],       'actions' => [['type' => 'event', 'value' => 'hr.leave.cancelled']]],
                    ['name' => 'cancel_from_review',   'from' => 'manager_review','to' => 'cancelled',      'guards' => [['type' => 'condition', 'value' => 'is_requester']],       'actions' => [['type' => 'event', 'value' => 'hr.leave.cancelled']]],
                ],
            ], JSON_UNESCAPED_UNICODE),
        ],

        // ── 2. Contract Approval Workflow ──
        [
            'workflow_code'  => 'hr_contract_approval',
            'name_ar'        => 'اعتماد العقود',
            'name_en'        => 'Contract Approval',
            'description_ar' => 'دورة عمل إنشاء واعتماد وتجديد عقود الموظفين',
            'definition_json' => json_encode([
                'states' => [
                    'draft'            => ['label_ar' => 'مسودة',               'label_en' => 'Draft',             'type' => 'initial'],
                    'pending_approval' => ['label_ar' => 'في انتظار الاعتماد',  'label_en' => 'Pending Approval',  'type' => 'intermediate'],
                    'active'           => ['label_ar' => 'ساري',                'label_en' => 'Active',            'type' => 'intermediate'],
                    'renewed'          => ['label_ar' => 'تم التجديد',          'label_en' => 'Renewed',           'type' => 'terminal'],
                    'expired'          => ['label_ar' => 'منتهي',               'label_en' => 'Expired',           'type' => 'terminal'],
                    'terminated'       => ['label_ar' => 'تم إنهاؤه',           'label_en' => 'Terminated',        'type' => 'terminal'],
                    'rejected'         => ['label_ar' => 'مرفوض',               'label_en' => 'Rejected',          'type' => 'terminal'],
                ],
                'transitions' => [
                    ['name' => 'submit_for_approval', 'from' => 'draft',            'to' => 'pending_approval', 'guards' => [['type' => 'permission', 'value' => 'hr.contract.manage']],  'actions' => [['type' => 'event', 'value' => 'hr.contract.submitted']]],
                    ['name' => 'approve',             'from' => 'pending_approval', 'to' => 'active',           'guards' => [['type' => 'permission', 'value' => 'hr.contract.manage']],  'actions' => [['type' => 'event', 'value' => 'hr.contract.activated']]],
                    ['name' => 'reject',              'from' => 'pending_approval', 'to' => 'rejected',         'guards' => [['type' => 'permission', 'value' => 'hr.contract.manage']],  'actions' => [['type' => 'event', 'value' => 'hr.contract.rejected']]],
                    ['name' => 'renew',               'from' => 'active',           'to' => 'renewed',          'guards' => [['type' => 'permission', 'value' => 'hr.contract.manage']],  'actions' => [['type' => 'event', 'value' => 'hr.contract.renewed']]],
                    ['name' => 'expire',              'from' => 'active',           'to' => 'expired',          'guards' => [['type' => 'timeout', 'field' => 'end_date']],               'trigger' => 'automatic', 'actions' => [['type' => 'event', 'value' => 'hr.contract.expired']]],
                    ['name' => 'terminate',           'from' => 'active',           'to' => 'terminated',       'guards' => [['type' => 'permission', 'value' => 'hr.contract.manage']],  'actions' => [['type' => 'event', 'value' => 'hr.contract.terminated']]],
                ],
            ], JSON_UNESCAPED_UNICODE),
        ],

        // ── 3. Loan Approval Workflow ──
        [
            'workflow_code'  => 'hr_loan_approval',
            'name_ar'        => 'اعتماد السلف والقروض',
            'name_en'        => 'Loan Approval',
            'description_ar' => 'دورة عمل طلب واعتماد السلف والقروض للموظفين',
            'definition_json' => json_encode([
                'states' => [
                    'submitted'        => ['label_ar' => 'تم التقديم',          'label_en' => 'Submitted',         'type' => 'initial'],
                    'manager_review'   => ['label_ar' => 'مراجعة المدير',       'label_en' => 'Manager Review',    'type' => 'intermediate'],
                    'hr_review'        => ['label_ar' => 'مراجعة الموارد البشرية', 'label_en' => 'HR Review',      'type' => 'intermediate'],
                    'finance_review'   => ['label_ar' => 'مراجعة المالية',      'label_en' => 'Finance Review',    'type' => 'intermediate'],
                    'approved'         => ['label_ar' => 'معتمد',               'label_en' => 'Approved',          'type' => 'intermediate'],
                    'disbursed'        => ['label_ar' => 'تم الصرف',            'label_en' => 'Disbursed',         'type' => 'intermediate'],
                    'repaying'         => ['label_ar' => 'جاري السداد',         'label_en' => 'Repaying',          'type' => 'intermediate'],
                    'settled'          => ['label_ar' => 'تم السداد',           'label_en' => 'Settled',           'type' => 'terminal'],
                    'rejected'         => ['label_ar' => 'مرفوض',               'label_en' => 'Rejected',          'type' => 'terminal'],
                    'cancelled'        => ['label_ar' => 'ملغى',                'label_en' => 'Cancelled',         'type' => 'terminal'],
                ],
                'transitions' => [
                    ['name' => 'submit_to_manager',  'from' => 'submitted',      'to' => 'manager_review',  'guards' => [['type' => 'permission', 'value' => 'hr.loan.manage']],     'actions' => [['type' => 'event', 'value' => 'hr.loan.submitted']]],
                    ['name' => 'manager_approve',    'from' => 'manager_review', 'to' => 'hr_review',       'guards' => [['type' => 'permission', 'value' => 'hr.loan.approve']],    'actions' => []],
                    ['name' => 'manager_reject',     'from' => 'manager_review', 'to' => 'rejected',        'guards' => [['type' => 'permission', 'value' => 'hr.loan.approve']],    'actions' => [['type' => 'event', 'value' => 'hr.loan.rejected']]],
                    ['name' => 'hr_approve',          'from' => 'hr_review',     'to' => 'finance_review',  'guards' => [['type' => 'permission', 'value' => 'hr.loan.approve']],    'actions' => []],
                    ['name' => 'hr_reject',            'from' => 'hr_review',    'to' => 'rejected',        'guards' => [['type' => 'permission', 'value' => 'hr.loan.approve']],    'actions' => [['type' => 'event', 'value' => 'hr.loan.rejected']]],
                    ['name' => 'finance_approve',      'from' => 'finance_review','to' => 'approved',       'guards' => [['type' => 'permission', 'value' => 'hr.loan.approve']],    'actions' => [['type' => 'event', 'value' => 'hr.loan.approved']]],
                    ['name' => 'finance_reject',       'from' => 'finance_review','to' => 'rejected',       'guards' => [['type' => 'permission', 'value' => 'hr.loan.approve']],    'actions' => [['type' => 'event', 'value' => 'hr.loan.rejected']]],
                    ['name' => 'disburse',             'from' => 'approved',      'to' => 'disbursed',      'guards' => [['type' => 'permission', 'value' => 'hr.loan.manage']],     'actions' => [['type' => 'event', 'value' => 'hr.loan.disbursed']]],
                    ['name' => 'start_repayment',      'from' => 'disbursed',     'to' => 'repaying',       'guards' => [],                                                          'trigger' => 'automatic', 'actions' => []],
                    ['name' => 'settle',               'from' => 'repaying',      'to' => 'settled',        'guards' => [['type' => 'condition', 'value' => 'all_installments_paid']],'actions' => [['type' => 'event', 'value' => 'hr.loan.settled']]],
                    ['name' => 'cancel',               'from' => 'submitted',     'to' => 'cancelled',      'guards' => [['type' => 'condition', 'value' => 'is_requester']],        'actions' => [['type' => 'event', 'value' => 'hr.loan.cancelled']]],
                ],
            ], JSON_UNESCAPED_UNICODE),
        ],

        // ── 4. End of Service Workflow ──
        [
            'workflow_code'  => 'hr_end_of_service',
            'name_ar'        => 'إنهاء الخدمة',
            'name_en'        => 'End of Service',
            'description_ar' => 'دورة عمل حساب واعتماد وصرف مستحقات نهاية الخدمة',
            'definition_json' => json_encode([
                'states' => [
                    'draft'            => ['label_ar' => 'مسودة',               'label_en' => 'Draft',             'type' => 'initial'],
                    'calculated'       => ['label_ar' => 'تم الحساب',           'label_en' => 'Calculated',        'type' => 'intermediate'],
                    'pending_approval' => ['label_ar' => 'في انتظار الاعتماد',  'label_en' => 'Pending Approval',  'type' => 'intermediate'],
                    'approved'         => ['label_ar' => 'معتمد',               'label_en' => 'Approved',          'type' => 'intermediate'],
                    'paid'             => ['label_ar' => 'تم الصرف',            'label_en' => 'Paid',              'type' => 'terminal'],
                    'cancelled'        => ['label_ar' => 'ملغى',                'label_en' => 'Cancelled',         'type' => 'terminal'],
                ],
                'transitions' => [
                    ['name' => 'calculate',          'from' => 'draft',            'to' => 'calculated',       'guards' => [['type' => 'permission', 'value' => 'hr.eos.manage']],    'actions' => [['type' => 'event', 'value' => 'hr.eos.calculated']]],
                    ['name' => 'submit_for_approval','from' => 'calculated',       'to' => 'pending_approval', 'guards' => [['type' => 'permission', 'value' => 'hr.eos.manage']],    'actions' => [['type' => 'event', 'value' => 'hr.eos.submitted']]],
                    ['name' => 'recalculate',        'from' => 'calculated',       'to' => 'draft',            'guards' => [['type' => 'permission', 'value' => 'hr.eos.manage']],    'actions' => []],
                    ['name' => 'approve',            'from' => 'pending_approval', 'to' => 'approved',         'guards' => [['type' => 'permission', 'value' => 'hr.eos.approve']],   'actions' => [['type' => 'event', 'value' => 'hr.eos.approved']]],
                    ['name' => 'reject',             'from' => 'pending_approval', 'to' => 'calculated',       'guards' => [['type' => 'permission', 'value' => 'hr.eos.approve']],   'actions' => [['type' => 'event', 'value' => 'hr.eos.rejected']]],
                    ['name' => 'pay',                'from' => 'approved',         'to' => 'paid',             'guards' => [['type' => 'permission', 'value' => 'hr.eos.approve']],   'actions' => [['type' => 'event', 'value' => 'hr.eos.paid']]],
                    ['name' => 'cancel',             'from' => 'draft',            'to' => 'cancelled',        'guards' => [['type' => 'permission', 'value' => 'hr.eos.manage']],    'actions' => [['type' => 'event', 'value' => 'hr.eos.cancelled']]],
                    ['name' => 'cancel_calculated',  'from' => 'calculated',       'to' => 'cancelled',        'guards' => [['type' => 'permission', 'value' => 'hr.eos.manage']],    'actions' => [['type' => 'event', 'value' => 'hr.eos.cancelled']]],
                ],
            ], JSON_UNESCAPED_UNICODE),
        ],

        // ── 5. Disciplinary Action Workflow ──
        [
            'workflow_code'  => 'hr_disciplinary',
            'name_ar'        => 'الإجراءات التأديبية',
            'name_en'        => 'Disciplinary Action',
            'description_ar' => 'دورة عمل الإجراءات التأديبية والتحقيق والعقوبات والتظلم وفقاً لقانون العمل المصري (المواد 58-68)',
            'definition_json' => json_encode([
                'states' => [
                    'reported'          => ['label_ar' => 'تم الإبلاغ',          'label_en' => 'Reported',          'type' => 'initial'],
                    'under_investigation'=> ['label_ar' => 'تحت التحقيق',       'label_en' => 'Under Investigation','type' => 'intermediate'],
                    'investigation_done'=> ['label_ar' => 'انتهى التحقيق',      'label_en' => 'Investigation Done','type' => 'intermediate'],
                    'penalty_decided'   => ['label_ar' => 'تم تحديد العقوبة',   'label_en' => 'Penalty Decided',   'type' => 'intermediate'],
                    'enforced'          => ['label_ar' => 'تم التنفيذ',          'label_en' => 'Enforced',          'type' => 'intermediate'],
                    'appealed'          => ['label_ar' => 'تم التظلم',           'label_en' => 'Appealed',          'type' => 'intermediate'],
                    'appeal_reviewed'   => ['label_ar' => 'تم مراجعة التظلم',   'label_en' => 'Appeal Reviewed',   'type' => 'intermediate'],
                    'upheld'            => ['label_ar' => 'تم تأييد العقوبة',   'label_en' => 'Upheld',            'type' => 'terminal'],
                    'modified'          => ['label_ar' => 'تم تعديل العقوبة',   'label_en' => 'Modified',          'type' => 'terminal'],
                    'overturned'        => ['label_ar' => 'تم إلغاء العقوبة',   'label_en' => 'Overturned',        'type' => 'terminal'],
                    'dismissed'         => ['label_ar' => 'تم الحفظ',            'label_en' => 'Dismissed',         'type' => 'terminal'],
                    'closed'            => ['label_ar' => 'مغلق',                'label_en' => 'Closed',            'type' => 'terminal'],
                ],
                'transitions' => [
                    ['name' => 'start_investigation','from' => 'reported',           'to' => 'under_investigation','guards' => [['type' => 'permission', 'value' => 'hr.disciplinary.manage']], 'actions' => [['type' => 'event', 'value' => 'hr.disciplinary.investigation_started']]],
                    ['name' => 'dismiss',           'from' => 'reported',            'to' => 'dismissed',          'guards' => [['type' => 'permission', 'value' => 'hr.disciplinary.manage']], 'actions' => [['type' => 'event', 'value' => 'hr.disciplinary.dismissed']]],
                    ['name' => 'complete_investigation','from' => 'under_investigation','to' => 'investigation_done','guards' => [['type' => 'permission', 'value' => 'hr.disciplinary.manage']], 'actions' => []],
                    ['name' => 'decide_penalty',    'from' => 'investigation_done',  'to' => 'penalty_decided',    'guards' => [['type' => 'permission', 'value' => 'hr.disciplinary.manage']], 'actions' => [['type' => 'event', 'value' => 'hr.disciplinary.penalty_decided']]],
                    ['name' => 'dismiss_after_investigation','from' => 'investigation_done','to' => 'dismissed',   'guards' => [['type' => 'permission', 'value' => 'hr.disciplinary.manage']], 'actions' => [['type' => 'event', 'value' => 'hr.disciplinary.dismissed']]],
                    ['name' => 'enforce',           'from' => 'penalty_decided',     'to' => 'enforced',           'guards' => [['type' => 'permission', 'value' => 'hr.disciplinary.manage']], 'actions' => [['type' => 'event', 'value' => 'hr.disciplinary.enforced']]],
                    ['name' => 'appeal',            'from' => 'enforced',            'to' => 'appealed',           'guards' => [['type' => 'condition', 'value' => 'within_7_day_appeal_window']], 'actions' => [['type' => 'event', 'value' => 'hr.disciplinary.appealed']]],
                    ['name' => 'close_no_appeal',   'from' => 'enforced',            'to' => 'closed',             'guards' => [['type' => 'timeout', 'days' => 7]], 'trigger' => 'automatic', 'actions' => [['type' => 'event', 'value' => 'hr.disciplinary.closed']]],
                    ['name' => 'review_appeal',     'from' => 'appealed',            'to' => 'appeal_reviewed',    'guards' => [['type' => 'permission', 'value' => 'hr.disciplinary.manage']], 'actions' => []],
                    ['name' => 'uphold',            'from' => 'appeal_reviewed',     'to' => 'upheld',             'guards' => [['type' => 'permission', 'value' => 'hr.disciplinary.manage']], 'actions' => [['type' => 'event', 'value' => 'hr.disciplinary.upheld']]],
                    ['name' => 'modify',            'from' => 'appeal_reviewed',     'to' => 'modified',           'guards' => [['type' => 'permission', 'value' => 'hr.disciplinary.manage']], 'actions' => [['type' => 'event', 'value' => 'hr.disciplinary.modified']]],
                    ['name' => 'overturn',          'from' => 'appeal_reviewed',     'to' => 'overturned',         'guards' => [['type' => 'permission', 'value' => 'hr.disciplinary.manage']], 'actions' => [['type' => 'event', 'value' => 'hr.disciplinary.overturned']]],
                ],
            ], JSON_UNESCAPED_UNICODE),
        ],
    ];

    foreach ($definitions as $def) {
        $existing = $db->selectOne(
            "SELECT id FROM workflow_definitions WHERE workflow_code = ?",
            [$def['workflow_code']]
        );
        if ($existing) {
            continue;
        }
        $db->insert('workflow_definitions', [
            'workflow_code'   => $def['workflow_code'],
            'name_ar'         => $def['name_ar'],
            'name_en'         => $def['name_en'],
            'description_ar'  => $def['description_ar'],
            'definition_json' => $def['definition_json'],
            'version'         => 1,
            'is_active'       => 1,
            'created_at'      => $ts,
            'updated_at'      => $ts,
        ]);
    }
};
