<?php

namespace App\Controllers;

use App\Models\RegistrationModel;
use App\Models\CourseModel;

class Admin extends BaseController
{
    /** Auth check helper */
    private function requireAuth()
    {
        if (!session()->get('admin_logged_in')) {
            return false;
        }
        return true;
    }

    // ─────────────────────────────────────────────
    // Main entry — login + student logbook
    // ─────────────────────────────────────────────
    public function index()
    {
        $session = session();

        // Handle POST login
        if (strtoupper($this->request->getMethod()) === 'POST') {
            $password = $this->request->getPost('password');
            if ($password === 'admin@genx') {
                $session->set('admin_logged_in', true);
                return redirect()->to(site_url('admin'));
            } else {
                $data['error'] = 'Invalid password. Please try again.';
                return view('admin_login', $data);
            }
        }

        // Handle logout
        if ($this->request->getGet('action') === 'logout') {
            $session->remove('admin_logged_in');
            return redirect()->to(site_url('admin'));
        }

        // Gate
        if (!$session->get('admin_logged_in')) {
            return view('admin_login');
        }

        $regModel    = new RegistrationModel();
        $courseModel = new CourseModel();

        $data['registrations'] = $regModel->orderBy('id', 'DESC')->findAll();

        // All courses with their lessons (for the course tab)
        $courseCodes = [
            'digital_marketing_foundational',
            'web_development_foundational',
            'ai_python_fullstack',
            'digital_marketing_expert',
        ];

        $data['courseCodes'] = $courseCodes;
        $data['allLessons']  = $courseModel->orderBy('course_code')->orderBy('module_order')->orderBy('lesson_order')->findAll();
        $data['activeTab']   = $this->request->getGet('tab') ?? 'students';

        return view('admin', $data);
    }

    // ═════════════════════════════════════════════
    // LESSON CRUD
    // ═════════════════════════════════════════════

    public function addLesson()
    {
        if (!$this->requireAuth()) {
            return $this->response->setStatusCode(403)->setJSON(['success' => false, 'error' => 'Unauthorized — please re-login.']);
        }

        $model = new CourseModel();

        $data = [
            'course_code'  => $this->request->getPost('course_code'),
            'course_type'  => $this->request->getPost('course_type'),
            'module_name'  => $this->request->getPost('module_name') ?: null,
            'module_order' => (int) ($this->request->getPost('module_order') ?: 1),
            'lesson_title' => $this->request->getPost('lesson_title'),
            'lesson_order' => (int) ($this->request->getPost('lesson_order') ?: 1),
            'youtube_url'  => $this->request->getPost('youtube_url') ?: null,
            'duration'     => $this->request->getPost('duration') ?: null,
            'notes'        => $this->request->getPost('notes') ?: null,
        ];

        if (empty($data['course_code']) || empty($data['lesson_title'])) {
            return $this->response->setJSON(['success' => false, 'error' => 'Course code and lesson title are required.']);
        }

        try {
            $result = $model->insert($data);
            if ($result === false) {
                $errors = $model->errors();
                $msg    = !empty($errors) ? implode(', ', $errors) : 'Database insert returned false.';
                return $this->response->setJSON(['success' => false, 'error' => $msg]);
            }
            return $this->response->setJSON(['success' => true, 'id' => $model->getInsertID()]);
        } catch (\Throwable $e) {
            return $this->response->setJSON(['success' => false, 'error' => 'DB error: ' . $e->getMessage()]);
        }
    }

    public function getLesson(int $id)
    {
        if (!$this->requireAuth()) {
            return $this->response->setStatusCode(403)->setJSON(['error' => 'Unauthorized']);
        }

        $model  = new CourseModel();
        $lesson = $model->find($id);

        if (!$lesson) {
            return $this->response->setStatusCode(404)->setJSON(['error' => 'Lesson not found']);
        }

        return $this->response->setJSON($lesson);
    }

    public function updateLesson(int $id)
    {
        if (!$this->requireAuth()) {
            return $this->response->setStatusCode(403)->setJSON(['success' => false, 'error' => 'Unauthorized — please re-login.']);
        }

        $model = new CourseModel();

        $data = [
            'course_code'  => $this->request->getPost('course_code'),
            'course_type'  => $this->request->getPost('course_type'),
            'module_name'  => $this->request->getPost('module_name') ?: null,
            'module_order' => (int) ($this->request->getPost('module_order') ?: 1),
            'lesson_title' => $this->request->getPost('lesson_title'),
            'lesson_order' => (int) ($this->request->getPost('lesson_order') ?: 1),
            'youtube_url'  => $this->request->getPost('youtube_url') ?: null,
            'duration'     => $this->request->getPost('duration') ?: null,
            'notes'        => $this->request->getPost('notes') ?: null,
        ];

        try {
            $model->update($id, $data);
            return $this->response->setJSON(['success' => true]);
        } catch (\Throwable $e) {
            return $this->response->setJSON(['success' => false, 'error' => 'DB error: ' . $e->getMessage()]);
        }
    }

    public function deleteLesson(int $id)
    {
        if (!$this->requireAuth()) {
            return $this->response->setStatusCode(403)->setJSON(['success' => false, 'error' => 'Unauthorized — please re-login.']);
        }

        try {
            $model = new CourseModel();
            $model->delete($id);
            return $this->response->setJSON(['success' => true]);
        } catch (\Throwable $e) {
            return $this->response->setJSON(['success' => false, 'error' => 'DB error: ' . $e->getMessage()]);
        }
    }

    // ═════════════════════════════════════════════
    // STUDENT CRUD
    // ═════════════════════════════════════════════

    public function addStudent()
    {
        if (!$this->requireAuth()) {
            return $this->response->setStatusCode(403)->setJSON(['success' => false, 'error' => 'Unauthorized']);
        }

        $model    = new RegistrationModel();
        $password = $this->request->getPost('password');

        $data = [
            'name'     => trim($this->request->getPost('name') ?? ''),
            'email'    => trim($this->request->getPost('email') ?? ''),
            'phone'    => trim($this->request->getPost('phone') ?? ''),
            'course'   => $this->request->getPost('course'),
            'batch'    => $this->request->getPost('batch') ?: 'weekday',
            'amount'   => (float) ($this->request->getPost('amount') ?: 0),
            'status'   => $this->request->getPost('status') ?: 'completed',
            'password' => !empty($password) ? password_hash($password, PASSWORD_DEFAULT) : '',
        ];

        if (empty($data['name']) || empty($data['email']) || empty($data['phone'])) {
            return $this->response->setJSON(['success' => false, 'error' => 'Name, email and phone are required.']);
        }

        if ($model->where('email', $data['email'])->first()) {
            return $this->response->setJSON(['success' => false, 'error' => 'A student with this email already exists.']);
        }

        try {
            $result = $model->insert($data);
            if ($result === false) {
                $errors = $model->errors();
                return $this->response->setJSON(['success' => false, 'error' => !empty($errors) ? implode(', ', $errors) : 'Insert failed.']);
            }
            return $this->response->setJSON(['success' => true, 'id' => $model->getInsertID()]);
        } catch (\Throwable $e) {
            return $this->response->setJSON(['success' => false, 'error' => 'DB error: ' . $e->getMessage()]);
        }
    }

    public function getStudent(int $id)
    {
        if (!$this->requireAuth()) {
            return $this->response->setStatusCode(403)->setJSON(['success' => false, 'error' => 'Unauthorized']);
        }

        $model   = new RegistrationModel();
        $student = $model->find($id);

        if (!$student) {
            return $this->response->setStatusCode(404)->setJSON(['success' => false, 'error' => 'Student not found']);
        }

        // Never expose hashed password to frontend
        unset($student['password'], $student['razorpay_order_id'], $student['razorpay_payment_id'], $student['razorpay_signature']);

        return $this->response->setJSON($student);
    }

    public function updateStudent(int $id)
    {
        if (!$this->requireAuth()) {
            return $this->response->setStatusCode(403)->setJSON(['success' => false, 'error' => 'Unauthorized']);
        }

        $model    = new RegistrationModel();
        $password = $this->request->getPost('password');

        $data = [
            'name'   => trim($this->request->getPost('name') ?? ''),
            'email'  => trim($this->request->getPost('email') ?? ''),
            'phone'  => trim($this->request->getPost('phone') ?? ''),
            'course' => $this->request->getPost('course'),
            'batch'  => $this->request->getPost('batch') ?: 'weekday',
            'amount' => (float) ($this->request->getPost('amount') ?: 0),
            'status' => $this->request->getPost('status') ?: 'completed',
        ];

        // Only update password if a new one is provided
        if (!empty($password)) {
            $data['password'] = password_hash($password, PASSWORD_DEFAULT);
        }

        if (empty($data['name']) || empty($data['email']) || empty($data['phone'])) {
            return $this->response->setJSON(['success' => false, 'error' => 'Name, email and phone are required.']);
        }

        try {
            $model->update($id, $data);
            return $this->response->setJSON(['success' => true]);
        } catch (\Throwable $e) {
            return $this->response->setJSON(['success' => false, 'error' => 'DB error: ' . $e->getMessage()]);
        }
    }

    public function deleteStudent(int $id)
    {
        if (!$this->requireAuth()) {
            return $this->response->setStatusCode(403)->setJSON(['success' => false, 'error' => 'Unauthorized']);
        }

        try {
            $model = new RegistrationModel();
            $model->delete($id);
            return $this->response->setJSON(['success' => true]);
        } catch (\Throwable $e) {
            return $this->response->setJSON(['success' => false, 'error' => 'DB error: ' . $e->getMessage()]);
        }
    }
}
