<?php
header("Content-Type: application/json");
include "db.php";

$method = $_SERVER["REQUEST_METHOD"];

/* ================= GET ================= */
if ($method === "GET") {

 $res = $conn->query(
  "SELECT id,hari,jam,aktif 
   FROM latihanty 
   ORDER BY id DESC"
 );

 $rows=[];
 while($r=$res->fetch_assoc()){
  $rows[]=$r;
 }

 echo json_encode($rows);
 exit;
}

/* ================= POST ================= */
if ($method === "POST") {

 $raw = file_get_contents("php://input");
 $data = json_decode($raw,true);

 if(!$data){
  echo json_encode(["error"=>"json invalid","raw"=>$raw]);
  exit;
 }

 if(empty($data["hari"]) || empty($data["jam"])){
  echo json_encode(["error"=>"hari/jam kosong"]);
  exit;
 }

 $hari = $conn->real_escape_string($data["hari"]);
 $jam  = $conn->real_escape_string($data["jam"]);

 // 🔥 HAPUS SEMUA JADWAL LAMA
 if(!$conn->query("DELETE FROM latihanty")){
  echo json_encode([
   "error"=>"gagal delete lama",
   "mysql"=>$conn->error
  ]);
  exit;
 }

 // 🔥 INSERT BARU
 $sql="
  INSERT INTO latihanty (hari,jam,aktif)
  VALUES ('$hari','$jam',1)
 ";

 if(!$conn->query($sql)){
  echo json_encode([
   "error"=>"insert gagal",
   "mysql"=>$conn->error
  ]);
  exit;
 }

 echo json_encode(["status"=>"ok"]);
 exit;
}

/* ================= DELETE ================= */
if ($method === "DELETE") {

 parse_str($_SERVER["QUERY_STRING"],$q);
 $id=intval($q["id"]??0);

 if($id){
  $conn->query("DELETE FROM latihanty WHERE id=$id");
 }

 echo json_encode(["status"=>"deleted"]);
 exit;
}

echo json_encode(["error"=>"method tidak valid"]);