<?php

declare(strict_types=1);

namespace App\Repositories;

final class InstructorAvailabilityRepository extends BaseRepository
{
    public function getForInstructor(int $instructorId): array
    {
        $stmt = $this->db->prepare(
            'SELECT * FROM instructor_availability
             WHERE instructor_id = :instructor_id
             ORDER BY weekday, time_from'
        );
        $stmt->execute(['instructor_id' => $instructorId]);
        return $stmt->fetchAll();
    }

    public function getActiveForInstructor(int $instructorId): array
    {
        $stmt = $this->db->prepare(
            'SELECT * FROM instructor_availability
             WHERE instructor_id = :instructor_id AND is_active = 1
             ORDER BY weekday, time_from'
        );
        $stmt->execute(['instructor_id' => $instructorId]);
        return $stmt->fetchAll();
    }

    public function upsert(int $instructorId, array $entries): void
    {
        // Delete all existing, then insert new (full replace)
        $this->db->beginTransaction();
        try {
            $stmt = $this->db->prepare('DELETE FROM instructor_availability WHERE instructor_id = :instructor_id');
            $stmt->execute(['instructor_id' => $instructorId]);

            $insert = $this->db->prepare(
                'INSERT INTO instructor_availability (instructor_id, weekday, time_from, time_to, is_active)
                 VALUES (:instructor_id, :weekday, :time_from, :time_to, :is_active)'
            );
            foreach ($entries as $e) {
                $insert->execute([
                    'instructor_id' => $instructorId,
                    'weekday' => (int) $e['weekday'],
                    'time_from' => $e['time_from'],
                    'time_to' => $e['time_to'],
                    'is_active' => (int) ($e['is_active'] ?? 1),
                ]);
            }
            $this->db->commit();
        } catch (\Throwable $e) {
            $this->db->rollBack();
            throw $e;
        }
    }

    public function delete(int $id): bool
    {
        $stmt = $this->db->prepare('DELETE FROM instructor_availability WHERE id = :id RETURNING id');
        $stmt->execute(['id' => $id]);
        return (bool) $stmt->fetch();
    }
}