<?php
namespace Tshen\Controllers;
use Tshen\Database; use function Tshen\view; use function Tshen\redirect;

class StudioController {
    public function index() {
        // For simplicity, allow access when role is 'studio' or 'admin'
        if (($_SESSION['role'] ?? '') !== 'studio' && ($_SESSION['role'] ?? '') !== 'admin') { redirect('/'); }
        $classes = Database::run('SELECT * FROM classes ORDER BY date,time')->fetchAll();
        $bookings = Database::run('SELECT c.title,c.date,c.time,c.location, COUNT(b.id) as booked FROM classes c LEFT JOIN bookings b ON b.class_id=c.id GROUP BY c.id ORDER BY c.date,c.time')->fetchAll();
        return view('studio/index', ['title'=>'Studio','classes'=>$classes,'bookings'=>$bookings]);
    }
    public function create() {
        if (($_SESSION['role'] ?? '') !== 'studio' && ($_SESSION['role'] ?? '') !== 'admin') { redirect('/'); }
        if (!\Tshen\csrf_check()) { \Tshen\flash('error','Invalid request.'); return redirect('/studio'); }
        $title = $_POST['title'] ?? ''; $location = $_POST['location'] ?? ''; $date = $_POST['date'] ?? ''; $time = $_POST['time'] ?? '';
        if ($title && $location && $date && $time) {
            Database::run('INSERT INTO classes (title,location,date,time,capacity) VALUES (?,?,?,?,?)', [$title,$location,$date,$time,($_POST['capacity'] ?? 10)]);
            \Tshen\flash('success','Class created.');
        }
        redirect('/studio');
    }
    public function update() {
        if (($_SESSION['role'] ?? '') !== 'studio' && ($_SESSION['role'] ?? '') !== 'admin') { redirect('/'); }
        if (!\Tshen\csrf_check()) { \Tshen\flash('error','Invalid request.'); return redirect('/studio'); }
        $id = (int)($_POST['id'] ?? 0);
        $row = Database::run('SELECT * FROM classes WHERE id=?', [$id])->fetch();
        if ($row) {
            $title = trim($_POST['title'] ?? $row['title']);
            $location = trim($_POST['location'] ?? $row['location']);
            $date = $_POST['date'] ?? $row['date'];
            $time = $_POST['time'] ?? $row['time'];
            $capacity = (int)($_POST['capacity'] ?? $row['capacity']);
            Database::run('UPDATE classes SET title=?, location=?, date=?, time=?, capacity=? WHERE id=?', [$title,$location,$date,$time,$capacity,$id]);
            \Tshen\flash('success','Class updated.');
        }
        redirect('/studio');
    }
}