<?php
// /edenrms/pages/update_student.php
declare(strict_types=1);

@session_start();
if (session_status() === PHP_SESSION_ACTIVE) { @session_write_close(); }
@set_time_limit(90);

function out(int $code, array $j){
  if (!headers_sent()) { header('Content-Type: application/json; charset=utf-8'); http_response_code($code); }
  echo json_encode($j, JSON_UNESCAPED_UNICODE);
  exit;
}
function log_err(string $m){
  $d = __DIR__.'/../logs';
  if(!is_dir($d)) @mkdir($d,0775,true);
  @file_put_contents($d.'/update_student.log','['.date('Y-m-d H:i:s').'] '.$m."\n",FILE_APPEND);
}

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') out(405, ['ok'=>false,'error'=>'Use POST']);

$DEBUG = (($_GET['debug'] ?? '')==='1') || (($_POST['debug'] ?? '')==='1');
mysqli_report($DEBUG ? (MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT) : MYSQLI_REPORT_OFF);

/* ---- DB (reuse app config) ---- */
$mysqli = null;
@include_once __DIR__.'/../includes/auth.php';
if (function_exists('ec_db')) { $mysqli = @ec_db(); }
if (!$mysqli instanceof mysqli) {
  @include_once __DIR__.'/../includes/db.php';
  if (isset($conn) && $conn instanceof mysqli) $mysqli = $conn;
}
if (!$mysqli instanceof mysqli) {
  try { $mysqli = new mysqli('localhost','root','','edencamp_edencampus'); $mysqli->set_charset('utf8mb4'); }
  catch(Throwable $e){ log_err('DB connect fail: '.$e->getMessage()); out(500, ['ok'=>false,'error'=>$DEBUG?('DB connect fail: '.$e->getMessage()):'Update failed']); }
}
$mysqli->set_charset('utf8mb4');

/* ---- Helpers ---- */
function col_exists(mysqli $db, string $t, string $c): bool {
  static $cache=[]; $k="$t|$c"; if(isset($cache[$k])) return $cache[$k];
  $st=$db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=? LIMIT 1");
  $st->bind_param('ss',$t,$c); $st->execute(); $st->store_result(); $ok=$st->num_rows>0; $st->free_result(); $st->close();
  return $cache[$k]=$ok;
}
function nv(?string $v): ?string { $v=isset($v)?trim($v):null; return $v===''?null:$v; }

/* ---- ID ---- */
$id = (int)($_POST['id'] ?? $_POST['student_id'] ?? $_POST['sid'] ?? 0);
if ($id<=0) out(400, ['ok'=>false,'error'=>'Invalid student ID']);

/* ---- Upload dir ---- */
$uploadDir = realpath(__DIR__.'/..') ?: dirname(__DIR__);
$uploadDir .= DIRECTORY_SEPARATOR.'uploads';
if (!is_dir($uploadDir)) @mkdir($uploadDir, 0775, true);
if (!is_writable($uploadDir)) { log_err("Upload dir not writable: $uploadDir"); out(500,['ok'=>false,'error'=>$DEBUG?'Upload dir not writable':'Server cannot save images']); }

/* ---- Server-side compression helpers (GD) ---- */
function gd_image_from_file(string $path, string $mime) {
  switch ($mime) {
    case 'image/jpeg': return @imagecreatefromjpeg($path);
    case 'image/png':  return @imagecreatefrompng($path);
    case 'image/webp': return function_exists('imagecreatefromwebp') ? @imagecreatefromwebp($path) : null;
    case 'image/gif':  return @imagecreatefromgif($path);
    default: return null;
  }
}
function compress_to_jpeg(string $src, string $dst, int $maxW=800, int $maxH=800, int $quality=82): bool {
  $info = @getimagesize($src);
  if (!$info) return false;
  [$w,$h] = $info;
  $mime = $info['mime'] ?? '';
  $im = gd_image_from_file($src, $mime);
  if (!$im) return false;

  $ratio = min($maxW / $w, $maxH / $h, 1.0);
  $cw = (int)round($w * $ratio);
  $ch = (int)round($h * $ratio);

  $dstIm = imagecreatetruecolor($cw, $ch);
  // white BG for transparent PNG/WebP/GIF
  $white = imagecolorallocate($dstIm, 255,255,255);
  imagefilledrectangle($dstIm, 0,0, $cw,$ch, $white);

  imagecopyresampled($dstIm, $im, 0,0, 0,0, $cw,$ch, $w,$h);
  $ok = imagejpeg($dstIm, $dst, $quality);
  imagedestroy($dstIm);
  imagedestroy($im);
  return $ok;
}

/* ---- Optional photo upload ---- */
$photoFilename = null;
try {
  $file = $_FILES['avatar'] ?? ($_FILES['photo'] ?? null);
  if ($file && ($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE) {
    $up=$file; if (($up['error'] ?? UPLOAD_ERR_OK) !== UPLOAD_ERR_OK) { out(400, ['ok'=>false,'error'=>'Image upload failed (code '.$up['error'].')']); }
    $tmp=$up['tmp_name']??''; $size=(int)($up['size']??0); $name=(string)($up['name']??'');
    if (!$tmp || !is_uploaded_file($tmp)) out(400,['ok'=>false,'error'=>'Invalid uploaded file']);
    if ($size<=0) out(400,['ok'=>false,'error'=>'Empty file']);
    if ($size>16*1024*1024) out(400,['ok'=>false,'error'=>'Image too large (max 16MB)']);

    // Detect mime / ext
    $mime=''; if(function_exists('finfo_open')){$f=finfo_open(FILEINFO_MIME_TYPE); if($f){$mime=(string)finfo_file($f,$tmp); finfo_close($f);} }
    $extFromName=strtolower(pathinfo($name, PATHINFO_EXTENSION));
    $allow=['image/jpeg'=>'jpg','image/png'=>'png','image/webp'=>'webp','image/gif'=>'gif'];
    $ext = ($mime && isset($allow[$mime])) ? $allow[$mime] : (in_array($extFromName,['jpg','jpeg','png','webp','gif'],true) ? ($extFromName==='jpeg'?'jpg':$extFromName) : '');
    if (!$ext) out(400,['ok'=>false,'error'=>'Invalid image type']);

    // Read previous filename (to delete after replace)
    $old=null;
    if (col_exists($mysqli,'studentss','photograph')) {
      if ($r=$mysqli->query("SELECT photograph FROM studentss WHERE id={$id} LIMIT 1")) { $row=$r->fetch_assoc(); $old=$row['photograph']??null; $r->free(); }
    }

    // Save original upload first (temporary)
    $tmpName = 'student_'.$id.'_'.date('YmdHis').'.'.$ext;
    $tmpPath = $uploadDir.DIRECTORY_SEPARATOR.$tmpName;
    if (!@move_uploaded_file($tmp,$tmpPath)) { log_err('move_uploaded_file failed'); out(500,['ok'=>false,'error'=>'Failed to save image']); }

    // Recompress/convert to .jpg ≤ 800×800, q=82
    $finalJpg = $uploadDir.DIRECTORY_SEPARATOR.'student_'.$id.'_'.date('YmdHis').'_c.jpg';
    if (compress_to_jpeg($tmpPath, $finalJpg, 800, 800, 82)) {
      // remove the original temp saved file if different
      if (strcasecmp($finalJpg, $tmpPath) !== 0 && is_file($tmpPath)) @unlink($tmpPath);
      $photoFilename = basename($finalJpg);
    } else {
      // if compression failed, keep the original (renamed to .jpg if already jpeg, else keep ext)
      log_err('Server compression failed for '.$tmpPath);
      $photoFilename = basename($tmpPath);
    }

    // delete old photo if exists and different
    if ($old && $old!==$photoFilename) {
      $oldPath=$uploadDir.DIRECTORY_SEPARATOR.$old;
      if (is_file($oldPath)) @unlink($oldPath);
    }
  }
} catch(Throwable $e){
  log_err('Upload exception: '.$e->getMessage());
  out(500,['ok'=>false,'error'=>$DEBUG?('Upload error: '.$e->getMessage()):'Update failed']);
}

/* ---- Dynamic UPDATE ---- */
$table='studentss';
$skip = ['id','student_id','sid','debug'];
$sets=[]; $types=''; $vals=[];
foreach ($_POST as $k=>$v) {
  if (in_array($k,$skip,true)) continue;
  if ($k==='reg_no' || $k==='center_regno') $k='center_reg_no';
  if (!preg_match('/^[a-zA-Z0-9_]+$/',$k)) continue;
  if (!col_exists($mysqli,$table,$k)) continue;
  $sets[]="`$k`=?"; $types.='s'; $vals[]=nv(is_array($v)?null:(string)$v);
}
if ($photoFilename!==null && col_exists($mysqli,$table,'photograph')) { $sets[]="`photograph`=?"; $types.='s'; $vals[]=$photoFilename; }
if (!$sets) out(200, ['ok'=>true,'message'=>'Nothing to update']);

$sql="UPDATE `$table` SET ".implode(', ',$sets)." WHERE id = ?"; $types.='i'; $vals[]=$id;
try {
  $st=$mysqli->prepare($sql); $st->bind_param($types, ...$vals); $st->execute(); $rows=$st->affected_rows; $st->close();
  out(200, ['ok'=>true,'message'=>'OK','rows'=>$rows,'photo'=>$photoFilename]);
} catch(Throwable $e){
  log_err('SQL error: '.$e->getMessage().' | '.$sql);
  out(500,['ok'=>false,'error'=>$DEBUG?('SQL error: '.$e->getMessage()):'Update failed']);
}
