<?php
namespace Tshen\Controllers;

use Tshen\Models\ClassModel;
use Tshen\Database; use function Tshen\view; use function Tshen\require_auth; use function Tshen\auth_user; use function Tshen\redirect;

class ClassController
{
    private $classModel;

    public function __construct()
    {
        // try to pass PDO if available
        $pdo = $GLOBALS['pdo'] ?? null;
        $this->classModel = new ClassModel($pdo);
    }

    public function index()
    {
        $classes = $this->classModel->getAllClasses();

        // ensure correct path to views folder (src\Controllers -> ../../views)
        $view = __DIR__ . '/../../views/classes/index.php';
        if (!is_readable($view)) {
            // graceful error message in browser instead of fatal include error
            header('HTTP/1.1 500 Internal Server Error');
            echo 'View file not found: ' . htmlspecialchars($view);
            return;
        }

        require_once $view;
    }

    public function show()
    {
        // Expect ?id=NN on the querystring
        $id = (int)($_GET['id'] ?? 0);
        if ($id <= 0) {
            http_response_code(404);
            echo view('errors/404', ['title' => 'Not Found']);
            return;
        }

        // Try DB first, otherwise fall back to model sample data
        $class = null; $studio = null; $reviews = [];
        if (class_exists('\Tshen\\Database')) {
            try {
                $row = Database::run('SELECT * FROM classes WHERE id = ?', [$id])->fetch();
                if ($row) {
                    $class = $row;
                    $studio = Database::run('SELECT * FROM studios WHERE id = ?', [$row['studio_id'] ?? 0])->fetch() ?: ['name' => 'Studio', 'location' => $row['studio_name'] ?? ''];
                    $reviews = Database::run('SELECT r.*, u.email as user_name FROM reviews r LEFT JOIN users u ON u.id=r.user_id WHERE r.class_id = ?', [$id])->fetchAll();
                }
            } catch (\Throwable $e) {
                // ignore DB errors and fall back to model
                $class = null;
            }
        }

        if (!$class) {
            // fallback: use sample list and find the matching id
            $samples = $this->classModel->getAllClasses();
            foreach ($samples as $s) {
                if ((int)$s['id'] === $id) { $class = $s; break; }
            }
            if ($class) {
                $studio = ['name' => $class['studio_name'] ?? 'Studio', 'location' => $class['studio_name'] ?? ''];
            }
        }

        if (!$class) {
            http_response_code(404);
            echo view('errors/404', ['title' => 'Not Found']);
            return;
        }

        // Normalize class and studio arrays so the view can safely access expected keys
        $classData = [
            'id' => (int)($class['id'] ?? 0),
            'title' => $class['title'] ?? $class['name'] ?? '',
            'date' => $class['date'] ?? '',
            'time' => $class['time'] ?? '',
            'capacity' => isset($class['capacity']) ? (int)$class['capacity'] : 0,
            'credits' => isset($class['credits']) ? (int)$class['credits'] : (int)($class['cost'] ?? 1),
            'studio_name' => $class['studio_name'] ?? '',
            'contact' => $class['contact'] ?? '',
            'email' => $class['email'] ?? '',
            'image' => $class['image'] ?? ''
        ];

        $studioData = [
            'id' => (int)($studio['id'] ?? 0),
            'name' => $studio['name'] ?? $classData['studio_name'] ?? 'Studio',
            'location' => $studio['location'] ?? $classData['studio_name'] ?? '',
            'contact' => $studio['contact'] ?? $classData['contact'] ?? '',
            'email' => $studio['email'] ?? $classData['email'] ?? ''
        ];

        // Render show view (view helper includes header/footer)
        echo view('classes/show', ['title' => $classData['title'] ?: 'Class', 'class' => $classData, 'studio' => $studioData, 'reviews' => $reviews]);
    }

    public function book()
    {
        require_auth();
        if (!\Tshen\csrf_check()) { \Tshen\flash('error', 'Invalid request.'); return redirect('/classes'); }

        $user = auth_user();
        $classId = (int)($_POST['class_id'] ?? 0);
        if ($classId <= 0) { \Tshen\flash('error', 'Invalid class.'); return redirect('/classes'); }

        // Check class exists and cost
        $cost = 1; // default cost
        if (class_exists('Tshen\\Database')) {
            try {
                $row = Database::run('SELECT id, credits, capacity FROM classes WHERE id = ?', [$classId])->fetch();
                if ($row) {
                    $cost = (int)($row['credits'] ?? 1);
                    // check capacity (optional)
                    $cap = (int)($row['capacity'] ?? 0);
                    if ($cap > 0) {
                        $count = Database::run('SELECT COUNT(*) as cnt FROM bookings WHERE class_id = ? AND status = ?', [$classId, 'confirmed'])->fetch()['cnt'] ?? 0;
                        if ($count >= $cap) { \Tshen\flash('error','Class is fully booked.'); return redirect('/classes'); }
                    }
                }
            } catch (\Throwable $e) {
                // ignore and continue
            }
        }

        // Check user credits
        if (class_exists('Tshen\\Database')) {
            $userRow = Database::run('SELECT credits FROM users WHERE id = ?', [$user['id']])->fetch();
            $credits = (int)($userRow['credits'] ?? 0);
            if ($credits < $cost) { \Tshen\flash('error','Not enough credits.'); return redirect('/dashboard'); }

            // Create booking + deduct credit
            Database::run('INSERT INTO bookings (user_id, class_id, status) VALUES (?,?,?)', [$user['id'], $classId, 'confirmed']);
            Database::run('UPDATE users SET credits = credits - ? WHERE id = ?', [$cost, $user['id']]);
            \Tshen\flash('success','Booking confirmed.');
            return redirect('/dashboard');
        }

        // If no DB available, emulate success
        \Tshen\flash('success','Booking recorded (dev mode).');
        redirect('/dashboard');
    }
}