<?php
declare(strict_types=1);
require __DIR__.'/lib.php';if(!app_installed())redirect('install.php');boot_session();$error='';
if(isset($_GET['logout'])){$_SESSION=[];session_destroy();redirect('admin.php');}
if(!admin_logged_in()&&$_SERVER['REQUEST_METHOD']==='POST'){
 verify_csrf();if(!rate_limit('admin_login',5,900))$error='Demasiados intentos. Espere 15 minutos.';else{$u=trim((string)($_POST['username']??''));$p=(string)($_POST['password']??'');$st=db()->prepare('SELECT * FROM admins WHERE username=?');$st->execute([$u]);$a=$st->fetch();if($a&&password_verify($p,$a['password_hash'])){session_regenerate_id(true);$_SESSION['admin_id']=$a['id'];audit('admin_login');redirect('admin.php');}$error='Credenciales no válidas.';}
}
if(!admin_logged_in()):?><!doctype html><html lang="es"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex,nofollow"><title>Administración de correo docente</title><link rel="stylesheet" href="../assets/css/styles.css"><link rel="stylesheet" href="styles.css"></head><body class="mail-app"><main class="mail-shell narrow"><div class="mail-brand"><img src="../assets/img/logo.png" alt=""><div><b>U.E.N. Alberto Smith</b><span>Administración de correo docente</span></div></div><section class="mail-panel"><h1>Acceso administrativo</h1><?php if($error):?><div class="alert error"><?=h($error)?></div><?php endif;?><form method="post" class="mail-form"><input type="hidden" name="csrf" value="<?=h(csrf_token())?>"><label>Usuario<input name="username" autocomplete="username" required></label><label>Contraseña<input type="password" name="password" autocomplete="current-password" required></label><button class="btn btn-red" type="submit">Ingresar</button></form></section></main></body></html><?php exit;endif;

if($_SERVER['REQUEST_METHOD']==='POST'){
 verify_csrf();$action=(string)($_POST['action']??'');
 try{
  if($action==='add_teacher'){
   $ced=normalize_cedula((string)$_POST['cedula']);$name=trim((string)$_POST['full_name']);$email=normalize_email((string)$_POST['personal_email']);$phone=preg_replace('/[^0-9+]/','',(string)($_POST['phone']??''))??'';if(strlen($name)<5)throw new RuntimeException('Nombre incompleto.');
   $hash=cedula_hash($ced);$st=db()->prepare('SELECT id,status FROM teachers WHERE cedula_hash=?');$st->execute([$hash]);$existing=$st->fetch();
   if($existing){$st=db()->prepare("UPDATE teachers SET full_name=?,personal_email_enc=?,phone_enc=?,status=CASE WHEN status='active' THEN status ELSE 'authorized' END,updated_at=? WHERE id=?");$st->execute([$name,encrypt_value($email),$phone?encrypt_value($phone):null,date('c'),$existing['id']]);audit('teacher_updated',(int)$existing['id']);flash('success','Registro docente actualizado.');}
   else{$st=db()->prepare("INSERT INTO teachers(cedula_hash,cedula_last4,full_name,personal_email_enc,phone_enc,status,created_at,updated_at) VALUES(?,?,?,?,?,'authorized',?,?)");$st->execute([$hash,substr($ced,-4),$name,encrypt_value($email),$phone?encrypt_value($phone):null,date('c'),date('c')]);audit('teacher_authorized',(int)db()->lastInsertId());flash('success','Docente autorizado correctamente.');}
  }
  elseif($action==='toggle_teacher'){$id=(int)$_POST['teacher_id'];$status=(string)$_POST['new_status'];if(!in_array($status,['authorized','disabled'],true))throw new RuntimeException('Estado inválido.');db()->prepare("UPDATE teachers SET status=?,updated_at=? WHERE id=? AND status<>'active'")->execute([$status,date('c'),$id]);audit('teacher_status_changed',$id,['status'=>$status]);flash('success','Estado actualizado.');}
  elseif($action==='import_csv'){
   if(empty($_FILES['csv']['tmp_name'])||!is_uploaded_file($_FILES['csv']['tmp_name']))throw new RuntimeException('Seleccione un archivo CSV.');$fh=fopen($_FILES['csv']['tmp_name'],'rb');if(!$fh)throw new RuntimeException('No se pudo leer el archivo.');$count=0;$line=0;
   while(($row=fgetcsv($fh,2000,','))!==false){$line++;if($line===1&&stripos(implode(',',$row),'cedula')!==false)continue;if(count($row)<3)continue;try{$ced=normalize_cedula($row[0]);$name=trim($row[1]);$email=normalize_email($row[2]);$phone=preg_replace('/[^0-9+]/','',$row[3]??'')??'';$hash=cedula_hash($ced);$st=db()->prepare('SELECT id FROM teachers WHERE cedula_hash=?');$st->execute([$hash]);$ex=$st->fetch();if($ex){db()->prepare("UPDATE teachers SET full_name=?,personal_email_enc=?,phone_enc=?,status=CASE WHEN status='active' THEN status ELSE 'authorized' END,updated_at=? WHERE id=?")->execute([$name,encrypt_value($email),$phone?encrypt_value($phone):null,date('c'),$ex['id']]);}else{db()->prepare("INSERT INTO teachers(cedula_hash,cedula_last4,full_name,personal_email_enc,phone_enc,status,created_at,updated_at) VALUES(?,?,?,?,?,'authorized',?,?)")->execute([$hash,substr($ced,-4),$name,encrypt_value($email),$phone?encrypt_value($phone):null,date('c'),date('c')]);}$count++;}catch(Throwable $ignore){}}
   fclose($fh);audit('teachers_csv_import',null,['count'=>$count]);flash('success',"Se procesaron {$count} docentes.");
  }
 }catch(Throwable $e){flash('error',$e->getMessage());}
 redirect('admin.php');
}
$teachers=db()->query('SELECT * FROM teachers ORDER BY full_name')->fetchAll();$logs=db()->query('SELECT event,teacher_id,created_at FROM audit_log ORDER BY id DESC LIMIT 20')->fetchAll();$flashes=pull_flashes();
?><!doctype html><html lang="es"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex,nofollow"><title>Administración de correo docente</title><link rel="stylesheet" href="../assets/css/styles.css"><link rel="stylesheet" href="styles.css"></head><body class="mail-app admin-app"><header class="admin-head"><div><b>U.E.N. Alberto Smith</b><span>Registro de correo docente · 2026–2027</span></div><nav><a href="index.php">Vista docente</a><a href="<?=h(config()['webmail_url'])?>" target="_blank" rel="noopener">Webmail</a><a href="?logout=1">Cerrar sesión</a></nav></header><main class="admin-shell"><?php foreach($flashes as $f):?><div class="alert <?=h($f['type'])?>"><?=h($f['message'])?></div><?php endforeach;?><div class="admin-grid"><section class="mail-panel"><h1>Autorizar profesor</h1><p>La cédula se almacena únicamente como huella HMAC. El correo personal queda cifrado en el servidor.</p><form method="post" class="mail-form"><input type="hidden" name="csrf" value="<?=h(csrf_token())?>"><input type="hidden" name="action" value="add_teacher"><div class="form-two"><label>Cédula<input name="cedula" required inputmode="numeric"></label><label>Nombre y apellido<input name="full_name" required></label></div><div class="form-two"><label>Correo personal<input type="email" name="personal_email" required></label><label>Teléfono opcional<input name="phone"></label></div><button class="btn btn-red" type="submit">Autorizar docente</button></form></section><section class="mail-panel"><h2>Importación masiva</h2><p>CSV UTF-8 con columnas: <code>cedula,nombre,correo_personal,telefono</code>.</p><form method="post" enctype="multipart/form-data" class="mail-form"><input type="hidden" name="csrf" value="<?=h(csrf_token())?>"><input type="hidden" name="action" value="import_csv"><label>Archivo CSV<input type="file" name="csv" accept=".csv,text/csv" required></label><button class="btn btn-outline-dark" type="submit">Importar registros</button></form><p><a href="docentes-ejemplo.csv" download>Descargar plantilla CSV</a></p><div class="status-pill <?=cpanel_configured()?'ok':'warn'?>">API cPanel: <?=cpanel_configured()?'configurada':'pendiente'?></div></section></div><section class="mail-panel wide"><div class="panel-title"><div><h2>Profesores autorizados</h2><p><?=count($teachers)?> registros</p></div></div><div class="table-wrap"><table><thead><tr><th>Profesor</th><th>Cédula</th><th>Correo personal</th><th>Cuenta institucional</th><th>Estado</th><th>Acción</th></tr></thead><tbody><?php foreach($teachers as $t):?><tr><td><?=h($t['full_name'])?></td><td>••••<?=h($t['cedula_last4'])?></td><td><?=h(mask_email(decrypt_value($t['personal_email_enc'])))?></td><td><?=h($t['institutional_email']?:'—')?></td><td><span class="status-pill <?=h($t['status'])?>"><?=h($t['status'])?></span></td><td><?php if($t['status']!=='active'):?><form method="post"><input type="hidden" name="csrf" value="<?=h(csrf_token())?>"><input type="hidden" name="action" value="toggle_teacher"><input type="hidden" name="teacher_id" value="<?=$t['id']?>"><input type="hidden" name="new_status" value="<?=$t['status']==='disabled'?'authorized':'disabled'?>"><button class="text-button" type="submit"><?=$t['status']==='disabled'?'Habilitar':'Deshabilitar'?></button></form><?php else:?>Activa<?php endif;?></td></tr><?php endforeach;?></tbody></table></div></section><section class="mail-panel wide"><h2>Auditoría reciente</h2><div class="audit-list"><?php foreach($logs as $l):?><div><code><?=h($l['created_at'])?></code><span><?=h($l['event'])?></span><small><?=h($l['teacher_id']?'Docente #'.$l['teacher_id']:'Sistema')?></small></div><?php endforeach;?></div></section></main></body></html>
