<?php
// work_api.php — shared AJAX API for Daily Work (User + Admin)
require_once __DIR__ . '/admin/_bootstrap.php'; // has $conn, session_start()

header('Content-Type: application/json; charset=utf-8');
function json_out($arr){ echo json_encode($arr); exit; }

$is_admin   = !empty($_SESSION['admin_id']);
$admin_id   = $is_admin ? (int)$_SESSION['admin_id'] : 0;
$is_student = !empty($_SESSION['student_id']);
$student_id = $is_student ? (int)$_SESSION['student_id'] : 0;

if (!$is_admin && !$is_student) json_out(['ok'=>false,'error'=>'Not authenticated']);

$act = $_POST['action'] ?? $_GET['action'] ?? '';

// simple sanitizer
function h($s){return htmlspecialchars($s??'',ENT_QUOTES,'UTF-8');}
function upload_multi($files,$sub_id,$student_id){
  global $conn;
  $saved=[];
  if (empty($files['name'])) return $saved;
  $count=count($files['name']);
  for($i=0;$i<$count;$i++){
    if ($files['error'][$i]!=UPLOAD_ERR_OK) continue;
    $name=$files['name'][$i];
    $ext=strtolower(pathinfo($name,PATHINFO_EXTENSION));
    $cat='other';
    foreach([
      'image'=>['jpg','jpeg','png','gif','webp'],
      'video'=>['mp4','webm','mkv','mov'],
      'audio'=>['mp3','wav','ogg','m4a'],
      'doc'=>['pdf','doc','docx','ppt','pptx','xls','xlsx','txt'],
      'archive'=>['zip','rar','7z']
    ] as $k=>$arr) if(in_array($ext,$arr)) $cat=$k;

    $base="uploads/work/{$cat}/".date('Y')."/".date('m')."/{$student_id}";
    $fs=__DIR__."/{$base}";
    if(!is_dir($fs)) @mkdir($fs,0775,true);
    $safe=preg_replace('/[^a-zA-Z0-9_\.-]/','_',$name);
    $dest="$fs/".time().'_'.$safe;
    if(move_uploaded_file($files['tmp_name'][$i],$dest)){
      $rel="$base/".basename($dest);
      $st=mysqli_prepare($conn,"INSERT INTO daily_work_files(submission_id,file_path,file_type,original_name) VALUES (?,?,?,?)");
      mysqli_stmt_bind_param($st,"isss",$sub_id,$rel,$cat,$name);
      mysqli_stmt_execute($st); mysqli_stmt_close($st);
      $saved[]=$rel;
    }
  }
  return $saved;
}

/* ---------------- STUDENT actions ---------------- */
if($act==='student_submit'){
  if(!$is_student) json_out(['ok'=>false,'error'=>'Only students']);
  $title=trim($_POST['title']??''); $desc=trim($_POST['description']??'');
  $date=$_POST['work_date']??date('Y-m-d'); if(!$title) json_out(['ok'=>false,'error'=>'Title required']);
  $st=mysqli_prepare($conn,"INSERT INTO daily_work_submissions(student_id,work_date,title,description,points_max,status)
    VALUES (?,?,?,?,10,'SUBMITTED')");
  mysqli_stmt_bind_param($st,"isss",$student_id,$date,$title,$desc);
  mysqli_stmt_execute($st); $sid=mysqli_insert_id($conn); mysqli_stmt_close($st);
  if(!empty($_FILES['files'])) upload_multi($_FILES['files'],$sid,$student_id);
  json_out(['ok'=>true]);
}

if($act==='list_my_submissions'){
  if(!$is_student) json_out(['ok'=>false,'error'=>'Only students']);
  $rows=[]; $files=[];
  $q=mysqli_query($conn,"SELECT * FROM daily_work_submissions WHERE student_id={$student_id} ORDER BY created_at DESC");
  while($r=mysqli_fetch_assoc($q)){
    $r['obtained_marks']=$r['points_obtained']; $r['total_marks']=$r['points_max']; $rows[]=$r;
    $fid=$r['id'];
    $fs=mysqli_query($conn,"SELECT id,file_path,file_type,original_name FROM daily_work_files WHERE submission_id={$fid}");
    while($f=mysqli_fetch_assoc($fs)) $files[$fid][]=$f;
  }
  json_out(['ok'=>true,'submissions'=>$rows,'files'=>$files]);
}

if($act==='request_recheck'){
  if(!$is_student) json_out(['ok'=>false,'error'=>'Only students']);
  $sid=(int)$_POST['submission_id']; $note=trim($_POST['note']??'');
  mysqli_query($conn,"UPDATE daily_work_submissions SET status='RECHECK_REQUESTED', recheck_note='".mysqli_real_escape_string($conn,$note)."' WHERE id={$sid} AND student_id={$student_id}");
  json_out(['ok'=>true]);
}

/* ---------------- ADMIN actions ---------------- */
if($act==='admin_list_students'){
  if(!$is_admin) json_out(['ok'=>false,'error'=>'Admin only']);
  $r=mysqli_query($conn,"SELECT id,full_name AS name,email FROM students ORDER BY full_name");
  $out=[]; while($x=mysqli_fetch_assoc($r))$out[]=$x;
  json_out(['ok'=>true,'students'=>$out]);
}

if($act==='admin_list_submissions'){
  if(!$is_admin) json_out(['ok'=>false,'error'=>'Admin only']);
  $w=" WHERE 1=1 "; 
  $sid=(int)($_GET['student_id']??0);
  $status=$_GET['status']??'';
  $from=$_GET['from']??''; $to=$_GET['to']??'';
  if($sid>0) $w.=" AND s.student_id=$sid ";
  if(in_array($status,['SUBMITTED','REVIEWED','RECHECK_REQUESTED'])) $w.=" AND s.status='$status' ";
  if($from) $w.=" AND s.work_date>='$from' "; if($to) $w.=" AND s.work_date<='$to' ";
  $sql="SELECT s.id,s.title,s.work_date,s.status,s.points_obtained AS obtained_marks,st.full_name 
        FROM daily_work_submissions s JOIN students st ON st.id=s.student_id $w ORDER BY s.created_at DESC LIMIT 200";
  $q=mysqli_query($conn,$sql); $rows=[];
  while($r=mysqli_fetch_assoc($q)) $rows[]=$r;
  json_out(['ok'=>true,'rows'=>$rows]);
}

if($act==='admin_get_submission'){
  if(!$is_admin) json_out(['ok'=>false,'error'=>'Admin only']);
  $sid=(int)$_GET['submission_id'];
  $s=mysqli_fetch_assoc(mysqli_query($conn,"SELECT s.*,st.full_name FROM daily_work_submissions s JOIN students st ON st.id=s.student_id WHERE s.id=$sid"));
  $f=[];$q=mysqli_query($conn,"SELECT * FROM daily_work_files WHERE submission_id=$sid");
  while($r=mysqli_fetch_assoc($q))$f[]=$r;
  json_out(['ok'=>true,'submission'=>$s,'files'=>$f]);
}

if($act==='admin_grade'){
  if(!$is_admin) json_out(['ok'=>false,'error'=>'Admin only']);
  $sid=(int)$_POST['submission_id'];
  $marks=(float)$_POST['obtained_marks'];
  $fb=trim($_POST['feedback']??'');
  mysqli_query($conn,"UPDATE daily_work_submissions SET points_obtained=$marks, status='REVIEWED', admin_comment='".mysqli_real_escape_string($conn,$fb)."', admin_id=$admin_id WHERE id=$sid");
  json_out(['ok'=>true]);
}

if($act==='admin_recheck_resolve'){
  if(!$is_admin) json_out(['ok'=>false,'error'=>'Admin only']);
  $sid=(int)$_POST['submission_id']; $marks=(float)$_POST['obtained_marks']; $fb=trim($_POST['feedback']??'');
  mysqli_query($conn,"UPDATE daily_work_submissions SET points_obtained=$marks, status='REVIEWED', admin_comment='".mysqli_real_escape_string($conn,$fb)."', admin_id=$admin_id WHERE id=$sid");
  json_out(['ok'=>true]);
}

if($act==='admin_delete_file'){
  if(!$is_admin) json_out(['ok'=>false,'error'=>'Admin only']);
  $fid=(int)$_POST['file_id']; $q=mysqli_fetch_assoc(mysqli_query($conn,"SELECT file_path FROM daily_work_files WHERE id=$fid"));
  if($q){ $fp=__DIR__.'/'.$q['file_path']; if(is_file($fp)) unlink($fp); mysqli_query($conn,"DELETE FROM daily_work_files WHERE id=$fid"); }
  json_out(['ok'=>true]);
}

if($act==='admin_delete_submission'){
  if(!$is_admin) json_out(['ok'=>false,'error'=>'Admin only']);
  $sid=(int)$_POST['submission_id'];
  mysqli_query($conn,"DELETE FROM daily_work_submissions WHERE id=$sid");
  json_out(['ok'=>true]);
}

json_out(['ok'=>false,'error'=>'Unknown action']);
