<?php
declare(strict_types=1);

namespace App\Modules\Interviews\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Core\EventBus;
use App\Modules\Interviews\Models\Interview;
use App\Modules\Workflow\Services\WorkflowEngine;

class InterviewController extends Controller
{
    public function index(Request $request): Response
    {
        $filters = [
            'search'   => trim((string) $request->get('q', '')),
            'status'   => $request->get('status', ''),
            'decision' => $request->get('decision', ''),
            'date_from'=> $request->get('date_from', ''),
            'date_to'  => $request->get('date_to', ''),
        ];
        $page = max(1, (int) $request->get('page', 1));
        $result = Interview::search($filters, 25, $page);

        return $this->view('Interviews.Views.index', [
            'rows'       => $result['data'],
            'pagination' => $result['pagination'],
            'filters'    => $filters,
        ]);
    }

    public function schedule(Request $request, string $memberId): Response
    {
        $db = App::getInstance()->db();
        $member = $db->selectOne("SELECT * FROM members WHERE id = ? AND is_archived = 0", [(int) $memberId]);
        if (!$member) {
            return $this->redirect('/members')->withError('العضو غير موجود');
        }

        $existing = Interview::getPendingForMember((int) $memberId);

        return $this->view('Interviews.Views.schedule', [
            'member'   => $member,
            'existing' => $existing,
        ]);
    }

    public function storeSchedule(Request $request, string $memberId): Response
    {
        $db = App::getInstance()->db();
        $member = $db->selectOne("SELECT * FROM members WHERE id = ? AND is_archived = 0", [(int) $memberId]);
        if (!$member) {
            return $this->redirect('/members')->withError('العضو غير موجود');
        }

        $scheduledDate = trim($request->post('scheduled_date', ''));
        $scheduledTime = trim($request->post('scheduled_time', ''));
        $location = trim($request->post('location', ''));

        if ($scheduledDate === '') {
            return $this->redirect("/interviews/schedule/{$memberId}")->withError('تاريخ المقابلة مطلوب');
        }

        if ($scheduledDate < date('Y-m-d')) {
            return $this->redirect("/interviews/schedule/{$memberId}")->withError('لا يمكن تحديد تاريخ في الماضي');
        }

        $employee = App::getInstance()->currentEmployee();

        $interview = Interview::create([
            'member_id'          => (int) $memberId,
            'form_submission_id' => $member['form_submission_id'] ? (int) $member['form_submission_id'] : null,
            'scheduled_date'     => $scheduledDate,
            'scheduled_time'     => $scheduledTime ?: null,
            'location'           => $location ?: null,
            'decision'           => 'pending',
            'status'             => 'scheduled',
        ]);

        // Try to transition workflow
        if ($member['workflow_instance_id']) {
            try {
                WorkflowEngine::transition((int) $member['workflow_instance_id'], 'schedule_interview', 'تم تحديد موعد المقابلة');
            } catch (\Throwable $e) {
                // Non-blocking — workflow might not support this transition from current state
            }
        }

        EventBus::dispatch('interview.scheduled', [
            'interview_id' => (int) $interview->id,
            'member_id'    => (int) $memberId,
            'date'         => $scheduledDate,
            'time'         => $scheduledTime,
        ]);

        return $this->redirect('/interviews')->withSuccess('تم تحديد موعد المقابلة: ' . $scheduledDate . ($scheduledTime ? ' الساعة ' . $scheduledTime : ''));
    }

    public function reschedule(Request $request, string $id): Response
    {
        $db = App::getInstance()->db();
        $interview = $db->selectOne("SELECT i.*, m.full_name_ar as member_name FROM interviews i JOIN members m ON m.id = i.member_id WHERE i.id = ?", [(int) $id]);
        if (!$interview || $interview['decision'] !== 'pending') {
            return $this->redirect('/interviews')->withError('المقابلة غير موجودة أو تم البت فيها');
        }

        $newDate = trim($request->post('scheduled_date', ''));
        $newTime = trim($request->post('scheduled_time', ''));
        $reason = trim($request->post('reschedule_reason', ''));

        if ($newDate === '' || $reason === '') {
            return $this->redirect('/interviews')->withError('التاريخ الجديد وسبب التأجيل مطلوبان');
        }

        $db->update('interviews', [
            'rescheduled_from'  => $interview['scheduled_date'],
            'scheduled_date'    => $newDate,
            'scheduled_time'    => $newTime ?: null,
            'reschedule_reason' => $reason,
            'reschedule_count'  => (int) $interview['reschedule_count'] + 1,
            'updated_at'        => date('Y-m-d H:i:s'),
        ], '`id` = ?', [(int) $id]);

        EventBus::dispatch('interview.rescheduled', [
            'interview_id' => (int) $id,
            'member_id'    => (int) $interview['member_id'],
            'old_date'     => $interview['scheduled_date'],
            'new_date'     => $newDate,
            'reason'       => $reason,
        ]);

        return $this->redirect('/interviews')->withSuccess('تم تأجيل المقابلة إلى ' . $newDate);
    }

    public function decide(Request $request, string $id): Response
    {
        $db = App::getInstance()->db();
        $interview = $db->selectOne(
            "SELECT i.*, m.full_name_ar as member_name, m.membership_number, m.workflow_instance_id
             FROM interviews i JOIN members m ON m.id = i.member_id WHERE i.id = ?",
            [(int) $id]
        );
        if (!$interview) {
            return $this->redirect('/interviews')->withError('المقابلة غير موجودة');
        }

        if ($request->method() === 'GET') {
            return $this->view('Interviews.Views.decide', ['interview' => $interview]);
        }

        // POST — process decision
        $decision = trim($request->post('decision', ''));
        $decisionNotes = trim($request->post('decision_notes', ''));
        $boardMemberNames = trim($request->post('board_member_names', ''));
        $boardReference = trim($request->post('board_decision_reference', ''));

        if (!in_array($decision, ['accepted', 'rejected'])) {
            return $this->redirect("/interviews/{$id}/decide")->withError('يجب اختيار قبول أو رفض');
        }

        $employee = App::getInstance()->currentEmployee();

        $db->update('interviews', [
            'decision'                 => $decision,
            'decision_notes'           => $decisionNotes ?: null,
            'decision_date'            => date('Y-m-d H:i:s'),
            'board_member_names'       => $boardMemberNames ?: null,
            'board_decision_reference' => $boardReference ?: null,
            'status'                   => $decision === 'accepted' ? 'completed_accepted' : 'completed_rejected',
            'updated_at'               => date('Y-m-d H:i:s'),
            'updated_by'               => $employee ? (int) $employee->id : null,
        ], '`id` = ?', [(int) $id]);

        // Update member status
        $newMemberStatus = $decision === 'accepted' ? 'payment_pending' : 'rejected';
        $db->update('members', [
            'status'     => $newMemberStatus,
            'updated_at' => date('Y-m-d H:i:s'),
        ], '`id` = ?', [(int) $interview['member_id']]);

        // Transition workflow
        if ($interview['workflow_instance_id']) {
            try {
                $transitionName = $decision === 'accepted' ? 'accept' : 'reject';
                WorkflowEngine::transition((int) $interview['workflow_instance_id'], $transitionName, $decisionNotes ?: 'قرار مجلس الأمناء');
            } catch (\Throwable $e) {
                // Try alternate transition names
                try {
                    $altName = $decision === 'accepted' ? 'payment_completed' : 'reject_from_review';
                    WorkflowEngine::transition((int) $interview['workflow_instance_id'], $altName, $decisionNotes ?: 'قرار مجلس الأمناء');
                } catch (\Throwable $e2) {
                    // Non-blocking
                }
            }
        }

        EventBus::dispatch('interview.decided', [
            'interview_id' => (int) $id,
            'member_id'    => (int) $interview['member_id'],
            'decision'     => $decision,
            'notes'        => $decisionNotes,
        ]);

        $msg = $decision === 'accepted'
            ? 'تم قبول العضو — في انتظار السداد'
            : 'تم رفض طلب العضوية';

        return $this->redirect('/interviews')->withSuccess($msg);
    }

    public function memberInterviews(Request $request, string $memberId): Response
    {
        $interviews = Interview::getForMember((int) $memberId);
        $db = App::getInstance()->db();
        $member = $db->selectOne("SELECT * FROM members WHERE id = ?", [(int) $memberId]);

        return $this->view('Interviews.Views.index', [
            'rows'       => $interviews,
            'pagination' => ['last_page' => 1, 'current_page' => 1],
            'filters'    => ['search' => '', 'status' => '', 'decision' => '', 'date_from' => '', 'date_to' => ''],
            'member'     => $member,
        ]);
    }
}