<?php

namespace App\Http\Controllers\Voting;

use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CandidateController extends Controller
{
    public function store(Request $request, int $voting): RedirectResponse
    {
        $schoolId = $this->currentSchoolId($request);

        abort_unless($schoolId, 422, 'مدرسه مشخص نیست.');

        $data = $request->validate([
            'student_id' => ['nullable', 'integer'],
            'display_name' => ['required', 'string', 'max:190'],
            'slogan' => ['nullable', 'string', 'max:255'],
            'description' => ['nullable', 'string', 'max:2000'],
        ]);

        $votingExists = DB::table('votings')
            ->where('school_id', $schoolId)
            ->where('id', $voting)
            ->exists();

        abort_unless($votingExists, 404);

        DB::table('voting_candidates')->insert([
            'school_id' => $schoolId,
            'voting_id' => $voting,
            'student_id' => $data['student_id'] ?? null,
            'display_name' => $data['display_name'],
            'slogan' => $data['slogan'] ?? null,
            'description' => $data['description'] ?? null,
            'status' => 'approved',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        DB::table('voting_logs')->insert([
            'school_id' => $schoolId,
            'voting_id' => $voting,
            'user_id' => $request->user()?->id,
            'action' => 'candidate_added',
            'new_value' => json_encode(['display_name' => $data['display_name']]),
            'ip_address' => $request->ip(),
            'user_agent' => substr((string) $request->userAgent(), 0, 500),
            'created_at' => now(),
        ]);

        return redirect()->route('school.voting.manage', $voting)->with('success', 'کاندیدا ثبت شد.');
    }

    public function destroy(Request $request, int $voting, int $candidate): RedirectResponse
    {
        $schoolId = $this->currentSchoolId($request);

        $exists = DB::table('voting_candidates')
            ->where('id', $candidate)
            ->where('voting_id', $voting)
            ->where('school_id', $schoolId)
            ->exists();

        abort_unless($exists, 404);

        $candidateName = DB::table('voting_candidates')->where('id', $candidate)->value('display_name');

        DB::table('voting_candidates')->where('id', $candidate)->delete();

        DB::table('voting_logs')->insert([
            'school_id' => $schoolId,
            'voting_id' => $voting,
            'user_id' => $request->user()?->id,
            'action' => 'candidate_removed',
            'old_value' => json_encode(['display_name' => $candidateName, 'candidate_id' => $candidate]),
            'ip_address' => $request->ip(),
            'user_agent' => substr((string) $request->userAgent(), 0, 500),
            'created_at' => now(),
        ]);

        return redirect()->route('school.voting.manage', $voting)->with('success', 'کاندیدا حذف شد.');
    }
}
