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

class DashboardController {
    public function index() {
        require_auth();
        $user = auth_user();
        $bookings = Database::run('SELECT b.id, c.title as class_title, c.location as studio_name, c.date, c.time, b.status 
                                  FROM bookings b 
                                  JOIN classes c ON c.id=b.class_id 
                                  WHERE b.user_id=? ORDER BY c.date,c.time', [$user['id']])->fetchAll();
        $credits = Database::run('SELECT credits FROM users WHERE id=?', [$user['id']])->fetch()['credits'] ?? 0;
        return view('dashboard/index', ['title'=>'Dashboard','bookings'=>$bookings,'credits'=>$credits]);
    }
    public function cancel() {
        require_auth(); if (!\Tshen\csrf_check()) { \Tshen\flash('error','Invalid request.'); return redirect('/dashboard'); }
        $user = auth_user(); $bid = $_POST['booking_id'] ?? 0;
        $exists = Database::run('SELECT id FROM bookings WHERE id=? AND user_id=?', [$bid,$user['id']])->fetch();
        if ($exists) {
            Database::run('UPDATE bookings SET status=? WHERE id=?', ['cancelled',$bid]);
            Database::run('UPDATE users SET credits = credits + 1 WHERE id=?', [$user['id']]);
        }
        \Tshen\flash('success','Booking cancelled. Credit refunded.');
        redirect('/dashboard');
    }
    public function purchase() {
        require_auth(); if (!\Tshen\csrf_check()) { \Tshen\flash('error','Invalid request.'); return redirect('/dashboard'); }
        $user = auth_user(); $bundle = (int)($_POST['bundle'] ?? 0);
        $allowed = [1,3,5,10,15,20]; if (!in_array($bundle,$allowed)) redirect('/dashboard');
        Database::run('INSERT INTO credit_purchases (user_id,credits,expires_at) VALUES (?,?,DATE("now","+1 month"))', [$user['id'],$bundle]);
        Database::run('UPDATE users SET credits = credits + ? WHERE id=?', [$bundle,$user['id']]);
        \Tshen\flash('success','Credits purchased.');
        redirect('/dashboard');
    }
    public function redeem() {
        require_auth(); if (!\Tshen\csrf_check()) { \Tshen\flash('error','Invalid request.'); return redirect('/dashboard'); }
        $user = auth_user(); $code = trim($_POST['code'] ?? '');
        if (!$code) redirect('/dashboard');
        $row = Database::run('SELECT id,credits,used_by FROM credit_codes WHERE code=?', [$code])->fetch();
        if ($row && empty($row['used_by'])) {
            Database::run('UPDATE credit_codes SET used_by=? WHERE id=?', [$user['id'],$row['id']]);
            Database::run('UPDATE users SET credits = credits + ? WHERE id=?', [$row['credits'],$user['id']]);
        }
        \Tshen\flash('success','Code redeemed.');
        redirect('/dashboard');
    }
    public function profile() {
        require_auth();
        $user = auth_user();
        $userId = $user['id'];

        // Get user data
        $userData = Database::run('SELECT email, credits FROM users WHERE id = ?', [$userId])->fetch();

        // Get profile data
        $profileData = Database::run('SELECT * FROM user_profiles WHERE user_id = ?', [$userId])->fetch();
        if ($profileData && !empty($profileData['profile_picture'])) {
            // Normalize stored path (remove leading '/public' if present)
            if (strpos($profileData['profile_picture'], '/public') === 0) {
                $profileData['profile_picture'] = substr($profileData['profile_picture'], 7);
            }
        }

        if (!$profileData) {
            $profileData = [
                'first_name' => '',
                'last_name' => '',
                'phone' => '',
                'address' => '',
                'gender' => '',
                'bio' => '',
                'profile_picture' => '/icon.png'
            ];
        }

        return view('profile', ['title' => 'Profile', 'user' => $userData, 'profile' => $profileData]);
    }
    public static function bookings($db, $userId) {
        $stmt = $db->prepare('SELECT * FROM bookings WHERE user_id = ? ORDER BY class_time DESC');
        $stmt->execute([$userId]);
        $bookings = $stmt->fetchAll(PDO::FETCH_ASSOC);
        // render view: pass $bookings to views/dashboard/bookings.php
        include __DIR__.'/../views/dashboard/bookings.php';
    }
}