<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Models\Student;

class StudentController {
    public function index() {
        if (!Auth::hasPermission('students')) {
            redirect('/login');
            exit;
        }

        $studentModel = new Student();
        $params = [
            'search' => $_GET['search'] ?? '',
        ];

        $students = $studentModel->search($params);
        $title = 'Our Students';

        require_once __DIR__ . '/../../views/admin/students/index.php';
    }

    public function create() {
        if (!Auth::hasPermission('students')) {
            redirect('/login');
            exit;
        }
        $title = 'Register Student';
        require_once __DIR__ . '/../../views/admin/students/create.php';
    }

    public function edit() {
        if (!Auth::hasPermission('students')) {
            redirect('/login');
            exit;
        }
        
        if (!isset($_GET['id'])) {
            redirect('/admin/students');
            exit;
        }

        $studentModel = new Student();
        $student = $studentModel->find($_GET['id']);
        
        if (!$student) {
            redirect('/admin/students');
            exit;
        }

        $title = 'Edit Student';
        require_once __DIR__ . '/../../views/admin/students/edit.php';
    }

    public function view() {
        if (!Auth::hasPermission('students')) {
            redirect('/login');
            exit;
        }
        
        if (!isset($_GET['id'])) {
            redirect('/admin/students');
            exit;
        }

        $studentModel = new Student();
        $student = $studentModel->find($_GET['id']);
        
        if (!$student) {
            redirect('/admin/students');
            exit;
        }

        // Financial Data
        $db = \App\Core\Database::getInstance();
        
        // Stats
        $stats = $db->prepare("SELECT 
                                SUM(total_amount) as total_billed, 
                                SUM(paid_amount) as total_paid,
                                SUM(discount_amount) as total_discount,
                                COUNT(*) as invoice_count
                                FROM invoices WHERE student_id = :id");
        $stats->execute(['id' => $_GET['id']]);
        $financials = $stats->fetch();
        
        $totalPaid = $financials['total_paid'] ?? 0;
        $totalDue = ($financials['total_billed'] ?? 0) - ($financials['total_paid'] ?? 0) - ($financials['total_discount'] ?? 0);
        $invoiceCount = $financials['invoice_count'] ?? 0;

        // Invoices
        $stmtInvoices = $db->prepare("SELECT * FROM invoices WHERE student_id = :id ORDER BY id DESC LIMIT 5");
        $stmtInvoices->execute(['id' => $_GET['id']]);
        $recentInvoices = $stmtInvoices->fetchAll();

        // Payments
        $stmtPayments = $db->prepare("SELECT fp.*, i.title as invoice_title 
                                      FROM fee_payments fp 
                                      JOIN invoices i ON fp.invoice_id = i.id 
                                      WHERE fp.student_id = :id 
                                      ORDER BY fp.id DESC LIMIT 5");
        $stmtPayments->execute(['id' => $_GET['id']]);
        $recentPayments = $stmtPayments->fetchAll();

        $title = 'Student Profile';
        require_once __DIR__ . '/../../views/admin/students/show.php';
    }

    public function save() {
        if (!Auth::hasPermission('students')) {
            redirect('/login');
            exit;
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $studentModel = new Student();
            
            $data = [
                'name' => $_POST['name'] ?? '',
                'phone' => $_POST['phone'] ?? '',
                'alt_phone' => !empty($_POST['alt_phone']) ? $_POST['alt_phone'] : null,
                'email' => !empty($_POST['email']) ? $_POST['email'] : (($_POST['phone'] ?? '') . '@student.com'), // fallback email for login
                'status' => $_POST['status'] ?? 'Active',
                'address' => !empty($_POST['address']) ? $_POST['address'] : null,
                'guardian_name' => !empty($_POST['guardian_name']) ? $_POST['guardian_name'] : null,
                'guardian_phone' => !empty($_POST['guardian_phone']) ? $_POST['guardian_phone'] : null,
                'photo' => $_POST['existing_photo'] ?? null,
            ];

            if (!empty($_POST['id'])) {
                $data['id'] = $_POST['id'];
            }

            // Handle Photo Upload
            if (isset($_FILES['photo']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
                $uploadDir = __DIR__ . '/../../public/uploads/students/';
                if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
                
                $fileName = time() . '_' . basename($_FILES['photo']['name']);
                if (move_uploaded_file($_FILES['photo']['tmp_name'], $uploadDir . $fileName)) {
                    $data['photo'] = '/uploads/students/' . $fileName;
                }
            }

            $password = !empty($_POST['password']) ? $_POST['password'] : null;

            try {
                $studentId = $studentModel->save($data, $password);
                $_SESSION['toast'] = [
                    'message' => isset($data['id']) ? 'Student profile updated successfully!' : 'New student registered successfully!', 
                    'type' => 'success'
                ];
                redirect('/admin/students/view?id=' . $studentId);
                exit;
            } catch (\Exception $e) {
                $_SESSION['toast'] = ['message' => $e->getMessage(), 'type' => 'error'];
                // Redirect back to either edit or create page
                if (isset($data['id'])) {
                    redirect('/admin/students/edit?id=' . $data['id']);
                } else {
                    redirect('/admin/students/create');
                }
                exit;
            }
        }
        redirect('/admin/students');
        exit;
    }

    public function delete() {
        if (!Auth::hasPermission('students')) {
            redirect('/login');
            exit;
        }

        if (isset($_GET['id'])) {
            $studentModel = new Student();
            $studentModel->delete($_GET['id']);
            $_SESSION['toast'] = ['message' => 'Student record deleted permanently.', 'type' => 'info'];
        }
        redirect('/admin/students');
        exit;
    }

    public function resetPassword() {
        if (!Auth::hasPermission('students')) {
            redirect('/login');
            exit;
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id'], $_POST['new_password'])) {
            $studentModel = new Student();
            $student = $studentModel->find($_POST['id']);
            
            if ($student) {
                $hash = password_hash($_POST['new_password'], PASSWORD_DEFAULT);
                $db = \App\Core\Database::getInstance();
                $stmt = $db->prepare("UPDATE users SET password = :password WHERE email = :email");
                if ($stmt->execute(['password' => $hash, 'email' => $student['email']])) {
                    $_SESSION['toast'] = ['message' => 'Password reset successfully!', 'type' => 'success'];
                } else {
                    $_SESSION['toast'] = ['message' => 'Failed to update password.', 'type' => 'error'];
                }
                redirect('/admin/students/view?id=' . $_POST['id']);
            }
        }
        redirect('/admin/students');
        exit;
    }

    public function toggleFreeze() {
        if (!Auth::hasPermission('students')) {
            redirect('/login');
            exit;
        }
        
        if (isset($_GET['id'])) {
            $studentModel = new Student();
            $student = $studentModel->find($_GET['id']);
            if ($student) {
                $newStatus = $student['status'] === 'Frozen' ? 'Active' : 'Frozen';
                $db = \App\Core\Database::getInstance();
                $stmt = $db->prepare("UPDATE students SET status = :status WHERE id = :id");
                $stmt->execute(['status' => $newStatus, 'id' => $_GET['id']]);
                $_SESSION['toast'] = ['message' => "Student account $newStatus.", 'type' => 'info'];
                redirect('/admin/students/view?id=' . $_GET['id']);
            }
        }
        redirect('/admin/students');
        exit;
}
}
