<?php
$section = 'doctor_holidays';
$db = db();
$lang = $_SESSION['lang'];

// Handle Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'create' || $action === 'update') {
        $doctor_id = $_POST['doctor_id'] ?? '';
        $start_date = $_POST['start_date'] ?? '';
        $end_date = $_POST['end_date'] ?? '';
        $note = $_POST['note'] ?? '';
        $id = $_POST['id'] ?? '';

        if ($doctor_id && $start_date && $end_date) {
            if ($action === 'create') {
                $stmt = $db->prepare("INSERT INTO doctor_holidays (doctor_id, start_date, end_date, note) VALUES (?, ?, ?, ?)");
                $stmt->execute([$doctor_id, $start_date, $end_date, $note]);
                $_SESSION['flash_message'] = __('holiday_added_successfully');
            } else {
                $stmt = $db->prepare("UPDATE doctor_holidays SET doctor_id = ?, start_date = ?, end_date = ?, note = ? WHERE id = ?");
                $stmt->execute([$doctor_id, $start_date, $end_date, $note, $id]);
                $_SESSION['flash_message'] = __('holiday_updated_successfully');
            }
        }
    } elseif ($action === 'delete') {
        $id = $_POST['id'] ?? '';
        if ($id) {
            $stmt = $db->prepare("DELETE FROM doctor_holidays WHERE id = ?");
            $stmt->execute([$id]);
            $_SESSION['flash_message'] = __('holiday_deleted_successfully');
        }
    }
    // Redirect to avoid resubmission
    echo "<script>window.location.href='doctor_holidays.php';</script>";
    exit;
}

// Fetch Doctors for dropdown
$doctors = $db->query("SELECT id, name_$lang as name FROM doctors ORDER BY name_$lang ASC")->fetchAll(PDO::FETCH_ASSOC);

// Fetch Holidays
$holidays = $db->query("SELECT dh.*, d.name_$lang as doctor_name FROM doctor_holidays dh JOIN doctors d ON dh.doctor_id = d.id ORDER BY dh.start_date DESC")->fetchAll(PDO::FETCH_ASSOC);

?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h3 class="fw-bold text-secondary"><?php echo __('doctor_holidays'); ?></h3>
    <button class="btn btn-primary shadow-sm" data-bs-toggle="modal" data-bs-target="#holidayModal" onclick="showCreateModal()">
        <i class="bi bi-plus-lg me-1"></i> <?php echo __('add_holiday'); ?>
    </button>
</div>

<div class="card shadow-sm border-0">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead>
                    <tr>
                        <th><?php echo __('doctor'); ?></th>
                        <th><?php echo __('start_date'); ?></th>
                        <th><?php echo __('end_date'); ?></th>
                        <th><?php echo __('note'); ?></th>
                        <th class="text-end"><?php echo __('actions'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($holidays)): ?>
                    <tr>
                        <td colspan="5" class="text-center py-4 text-muted">
                            <i class="bi bi-calendar-x display-6 d-block mb-2"></i>
                            <?php echo __('no_holidays_found'); ?>
                        </td>
                    </tr>
                    <?php else: ?>
                        <?php foreach ($holidays as $h): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($h['doctor_name']); ?></td>
                            <td><?php echo htmlspecialchars($h['start_date']); ?></td>
                            <td><?php echo htmlspecialchars($h['end_date']); ?></td>
                            <td><?php echo htmlspecialchars($h['note']); ?></td>
                            <td class="text-end">
                                <button class="btn btn-sm btn-outline-primary me-1" onclick="showEditModal(<?php echo htmlspecialchars(json_encode($h)); ?>)">
                                    <i class="bi bi-pencil"></i>
                                </button>
                                <button class="btn btn-sm btn-outline-danger" onclick="deleteHoliday(<?php echo $h['id']; ?>)">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Modal -->
<div class="modal fade" id="holidayModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form method="POST" class="modal-content border-0 shadow">
            <input type="hidden" name="action" id="modalAction" value="create">
            <input type="hidden" name="id" id="holidayId">
            <div class="modal-header border-0 pb-0">
                <h5 class="modal-title fw-bold text-secondary" id="modalTitle"><?php echo __('add_holiday'); ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body pt-3">
                <div class="mb-3">
                    <label class="form-label small text-muted"><?php echo __('doctor'); ?></label>
                    <select name="doctor_id" id="doctorId" class="form-select" required>
                        <option value=""><?php echo __('select') . ' ' . __('doctor'); ?></option>
                        <?php foreach ($doctors as $d): ?>
                            <option value="<?php echo $d['id']; ?>"><?php echo htmlspecialchars($d['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label small text-muted"><?php echo __('start_date'); ?></label>
                        <input type="date" name="start_date" id="startDate" class="form-control" required>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label small text-muted"><?php echo __('end_date'); ?></label>
                        <input type="date" name="end_date" id="endDate" class="form-control" required>
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label small text-muted"><?php echo __('note'); ?></label>
                    <textarea name="note" id="note" class="form-control" rows="2"></textarea>
                </div>
            </div>
            <div class="modal-footer border-0 bg-light rounded-bottom">
                <button type="button" class="btn btn-secondary shadow-sm me-2" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                <button type="submit" class="btn btn-primary shadow-sm px-4"><i class="bi bi-check2-circle me-1"></i> <?php echo __('save'); ?></button>
            </div>
        </form>
    </div>
</div>

<!-- Delete Form -->
<form id="deleteForm" method="POST" style="display:none;">
    <input type="hidden" name="action" value="delete">
    <input type="hidden" name="id" id="deleteId">
</form>

<script>
function showCreateModal() {
    document.getElementById('modalTitle').innerText = '<?php echo __('add_holiday'); ?>';
    document.getElementById('modalAction').value = 'create';
    document.getElementById('holidayId').value = '';
    document.getElementById('doctorId').value = '';
    document.getElementById('startDate').value = '';
    document.getElementById('endDate').value = '';
    document.getElementById('note').value = '';
}

function showEditModal(data) {
    document.getElementById('modalTitle').innerText = '<?php echo __('edit_holiday'); ?>';
    document.getElementById('modalAction').value = 'update';
    document.getElementById('holidayId').value = data.id;
    document.getElementById('doctorId').value = data.doctor_id;
    document.getElementById('startDate').value = data.start_date;
    document.getElementById('endDate').value = data.end_date;
    document.getElementById('note').value = data.note;
    
    var modal = new bootstrap.Modal(document.getElementById('holidayModal'));
    modal.show();
}

function deleteHoliday(id) {
    if (confirm('<?php echo __('are_you_sure_delete_holiday'); ?>')) {
        document.getElementById('deleteId').value = id;
        document.getElementById('deleteForm').submit();
    }
}
</script>