<?php

declare(strict_types=1);
require DENTAL_ROOT . '/app/bootstrap.php';
require_login();
require_roles(['super_admin','clinic_admin']);
require DENTAL_ROOT . '/app/layout.php';

$pdo = db();
$branches = $pdo->query('SELECT id,name FROM `' . table('branches') . '` WHERE is_active=1 ORDER BY name')->fetchAll();
$branchId = (int) ($_GET['branch_id'] ?? $_POST['branch_id'] ?? ($branches[0]['id'] ?? 0));
$days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        verify_csrf();
        $action = (string) ($_POST['action'] ?? 'save_hours');
        if ($branchId < 1) throw new RuntimeException('Select a clinic branch.');
        if ($action === 'save_hours') {
            $stmt = $pdo->prepare('INSERT INTO `' . table('branch_operating_hours') . '` (branch_id,day_of_week,is_open,open_time,close_time,slot_interval_minutes,created_at) VALUES (?,?,?,?,?,?,NOW()) ON DUPLICATE KEY UPDATE is_open=VALUES(is_open),open_time=VALUES(open_time),close_time=VALUES(close_time),slot_interval_minutes=VALUES(slot_interval_minutes),updated_at=NOW()');
            for ($day=0; $day<=6; $day++) {
                $open = isset($_POST['is_open'][$day]);
                $start = trim((string) ($_POST['open_time'][$day] ?? ''));
                $end = trim((string) ($_POST['close_time'][$day] ?? ''));
                $interval = (int) ($_POST['slot_interval'][$day] ?? 30);
                if ($open && ($start === '' || $end === '' || time_minutes($end) <= time_minutes($start))) {
                    throw new RuntimeException($days[$day] . ' must have a valid opening and closing time.');
                }
                if (!in_array($interval, [5,10,15,20,30,45,60], true)) $interval = 30;
                $stmt->execute([$branchId,$day,$open?1:0,$open?$start:null,$open?$end:null,$interval]);
            }
            audit('branch_operation_hours_updated','branch',$branchId);
            flash('success','Clinic operation hours have been updated.');
        } elseif ($action === 'add_exception') {
            $date = (string) ($_POST['exception_date'] ?? '');
            $isOpen = isset($_POST['exception_is_open']);
            $start = trim((string) ($_POST['exception_open_time'] ?? ''));
            $end = trim((string) ($_POST['exception_close_time'] ?? ''));
            if (!$date || strtotime($date) === false) throw new RuntimeException('Select a valid exception date.');
            if ($isOpen && ($start === '' || $end === '' || time_minutes($end) <= time_minutes($start))) throw new RuntimeException('Enter valid special opening hours.');
            $stmt=$pdo->prepare('INSERT INTO `' . table('branch_operating_exceptions') . '` (branch_id,exception_date,is_open,open_time,close_time,reason,created_by,created_at) VALUES (?,?,?,?,?,?,?,NOW()) ON DUPLICATE KEY UPDATE is_open=VALUES(is_open),open_time=VALUES(open_time),close_time=VALUES(close_time),reason=VALUES(reason),created_by=VALUES(created_by),updated_at=NOW()');
            $stmt->execute([$branchId,$date,$isOpen?1:0,$isOpen?$start:null,$isOpen?$end:null,trim((string)($_POST['reason']??''))?:null,current_user()['id']]);
            audit('branch_operation_exception_saved','branch',$branchId,['date'=>$date,'is_open'=>$isOpen]);
            flash('success','Special clinic date saved.');
        } elseif ($action === 'delete_exception') {
            $id=(int)($_POST['exception_id']??0);
            $pdo->prepare('DELETE FROM `' . table('branch_operating_exceptions') . '` WHERE id=? AND branch_id=?')->execute([$id,$branchId]);
            audit('branch_operation_exception_deleted','branch',$branchId,['exception_id'=>$id]);
            flash('success','Special date removed.');
        }
        header('Location: operation_hours.php?branch_id='.$branchId);exit;
    } catch (Throwable $e) {$error=$e->getMessage();}
}

$hours=[];
$stmt=$pdo->prepare('SELECT * FROM `' . table('branch_operating_hours') . '` WHERE branch_id=?');$stmt->execute([$branchId]);
foreach($stmt->fetchAll() as $row)$hours[(int)$row['day_of_week']]=$row;
$exceptions=[];
if($branchId){$stmt=$pdo->prepare('SELECT * FROM `' . table('branch_operating_exceptions') . '` WHERE branch_id=? AND exception_date>=CURDATE() ORDER BY exception_date LIMIT 100');$stmt->execute([$branchId]);$exceptions=$stmt->fetchAll();}
render_header('Clinic Operation Hours');
?>
<?php if($error):?><div class="flash error"><?=e($error)?></div><?php endif;?>
<div class="toolbar"><div><strong>Branch hours define the maximum schedule.</strong><span class="muted">Doctors can only select availability inside these times.</span></div><a class="btn primary" href="doctor_schedule.php?branch_id=<?=$branchId?>">Doctor schedule builder</a></div>
<form method="get" class="card form-grid"><label>Clinic branch<select name="branch_id" onchange="this.form.submit()"><?php foreach($branches as $b):?><option value="<?=$b['id']?>" <?=$branchId===$b['id']?'selected':''?>><?=e($b['name'])?></option><?php endforeach;?></select></label></form>
<form method="post" class="card"><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="action" value="save_hours"><input type="hidden" name="branch_id" value="<?=$branchId?>"><div class="table-wrap"><table><thead><tr><th>Day</th><th>Open</th><th>Opening</th><th>Closing</th><th>Slot interval</th></tr></thead><tbody><?php foreach($days as $day=>$label):$r=$hours[$day]??['is_open'=>($day>=1&&$day<=6),'open_time'=>'08:00:00','close_time'=>$day===6?'12:00:00':'17:00:00','slot_interval_minutes'=>30];?><tr><td><strong><?=e($label)?></strong></td><td><input type="checkbox" name="is_open[<?=$day?>]" value="1" <?=$r['is_open']?'checked':''?> data-hours-toggle="<?=$day?>"></td><td><input type="time" name="open_time[<?=$day?>]" value="<?=e(substr((string)$r['open_time'],0,5))?>" data-hours-field="<?=$day?>"></td><td><input type="time" name="close_time[<?=$day?>]" value="<?=e(substr((string)$r['close_time'],0,5))?>" data-hours-field="<?=$day?>"></td><td><select name="slot_interval[<?=$day?>]" data-hours-field="<?=$day?>"><?php foreach([5,10,15,20,30,45,60] as $m):?><option value="<?=$m?>" <?=$m==(int)$r['slot_interval_minutes']?'selected':''?>><?=$m?> minutes</option><?php endforeach;?></select></td></tr><?php endforeach;?></tbody></table></div><div class="card-actions"><button class="btn primary" type="submit">Save operation hours</button></div></form>
<div class="grid two"><form method="post" class="card form-grid"><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="action" value="add_exception"><input type="hidden" name="branch_id" value="<?=$branchId?>"><h2 class="wide">Holiday or special date</h2><label>Date<input type="date" name="exception_date" min="<?=date('Y-m-d')?>" required></label><label class="check-label"><input type="checkbox" name="exception_is_open" value="1" data-exception-open><span>Clinic is open on this date</span></label><label>Opening time<input type="time" name="exception_open_time" value="08:00" data-exception-time></label><label>Closing time<input type="time" name="exception_close_time" value="17:00" data-exception-time></label><label class="wide">Reason<input name="reason" maxlength="255" placeholder="Holiday, maintenance, special clinic schedule"></label><button class="btn primary" type="submit">Save special date</button></form><div class="card"><h2>Upcoming special dates</h2><div class="table-wrap"><table><thead><tr><th>Date</th><th>Schedule</th><th></th></tr></thead><tbody><?php foreach($exceptions as $r):?><tr><td><?=e(date('M j, Y',strtotime($r['exception_date'])))?><br><small><?=e($r['reason'])?></small></td><td><?=$r['is_open']?e(date('g:i A',strtotime($r['open_time'])).'–'.date('g:i A',strtotime($r['close_time']))):'Closed'?></td><td><form method="post"><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="action" value="delete_exception"><input type="hidden" name="branch_id" value="<?=$branchId?>"><input type="hidden" name="exception_id" value="<?=$r['id']?>"><button class="btn ghost" type="submit">Remove</button></form></td></tr><?php endforeach;if(!$exceptions):?><tr><td colspan="3" class="empty-cell">No upcoming exceptions.</td></tr><?php endif;?></tbody></table></div></div></div>
<?php render_footer(); ?>
