<?php
include "../user/db.php";
$res = ['success'=>false];
if($_SERVER['REQUEST_METHOD']==='POST'){
    $id = intval($_POST['course_id']);
    $title = trim($_POST['course_title']);
    $tutor = trim($_POST['tutor']);
    $price = floatval($_POST['price']);

    // Handle cover
    if(!empty($_FILES['cover']['name'])){
        $ext = pathinfo($_FILES['cover']['name'],PATHINFO_EXTENSION);
        $cover = "../uploads/covers/cover_".uniqid().".$ext";
        move_uploaded_file($_FILES['cover']['tmp_name'],$cover);
        $conn->query("UPDATE courses SET cover='$cover' WHERE id=$id");
    }

    // Handle PDF
    if(!empty($_FILES['course_pdf']['name'])){
        $ext = pathinfo($_FILES['course_pdf']['name'],PATHINFO_EXTENSION);
        $pdf = "../uploads/course_outlines/outline_".uniqid().".$ext";
        move_uploaded_file($_FILES['course_pdf']['tmp_name'],$pdf);
        $conn->query("UPDATE courses SET course_outline_pdf='$pdf' WHERE id=$id");
    }

    // Update course
    $stmt = $conn->prepare("UPDATE courses SET title=?, tutor=?, price=? WHERE id=?");
    $stmt->bind_param("ssdi",$title,$tutor,$price,$id);
    $stmt->execute();
    $stmt->close();

    // Update modules
    if(isset($_POST['module_title'])){
        foreach($_POST['module_title'] as $modId=>$modTitle){
            $modTitle = trim($modTitle);
            if($modTitle==='') continue;
            $video_file=''; $pdf_file='';

            if(!empty($_FILES['module_video']['name'][$modId])){
                $ext = pathinfo($_FILES['module_video']['name'][$modId],PATHINFO_EXTENSION);
                $video_file = "../uploads/module_videos/vid_".uniqid().".$ext";
                move_uploaded_file($_FILES['module_video']['tmp_name'][$modId],$video_file);
            }

            if(!empty($_FILES['module_pdf']['name'][$modId])){
                $ext = pathinfo($_FILES['module_pdf']['name'][$modId],PATHINFO_EXTENSION);
                $pdf_file = "../uploads/modules/mod_".uniqid().".$ext";
                move_uploaded_file($_FILES['module_pdf']['tmp_name'][$modId],$pdf_file);
            }

            $q="UPDATE modules SET title='$modTitle'";
            if($video_file) $q.=", video_file='$video_file'";
            if($pdf_file) $q.=", pdf_file='$pdf_file'";
            $q.=" WHERE id=$modId";
            $conn->query($q);
        }
    }

    $res['success']=true;
}

echo json_encode($res);
