<?php
header('Content-Type: application/json');
// teacher_save_video.php
require 'db.php'; // Include the database connection

// Get POST data
$youtube_url = $_POST['youtube_url'];
$lesson_name = $_POST['lesson_title'];
$lesson_id = $_POST['lesson_id'];
$topic_id = $_POST['topic_id']; // Added topic_id
$youtube_desc = $_POST['lesson_description'];
$user_id = $_POST['user_id'];
$school_id = $_POST['school_id'];
$grade = $_POST['grade'];
$covered = 1;

// Validate input
// Updated validation to include topic_id and remove subject
if (empty($youtube_url) || empty($lesson_name) || empty($lesson_id) || empty($topic_id) || empty($user_id)) {
    echo json_encode(['status' => 'error', 'message' => 'All required fields (youtube_url, lesson_title, lesson_id, topic_id, user_id) must be provided']);
    exit;
}

// Insert data into the database
// Updated SQL query to include topic_id and remove subject
$sql = "INSERT INTO tbl_videos (youtube_url, lesson_name, lesson_id, topic_id, youtube_desc, user_id, grade) VALUES (?, ?, ?, ?, ?, ?, ?)";
//lets save to curriculum coverage too
$sqlCC = "INSERT INTO curriculum_coverage (school_id, user_id, topic_id, lesson_id, covered, grade) VALUES (?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt2 = $conn->prepare($sqlCC);
// Updated bind_param to include topic_id (assuming it's an integer, 'i') and match the new column order.
// If topic_id is a string, use 's'. Adjust the type 'i' for lesson_id if it's not an integer.
// Assuming lesson_id and topic_id are integers. If they are strings, change 'ii' to 'ss' or accordingly.
$stmt->bind_param("sssssss", $youtube_url, $lesson_name, $lesson_id, $topic_id, $youtube_desc, $user_id, $grade);
$stmt2->bind_param("sssss", $school_id, $user_id, $topic_id, $lesson_id, $covered);

if ($stmt->execute()) {    
    // echo json_encode(['status' => 'success', 'message' => 'Transcribing Video Now.....']);
    // Include transcribe_video.php directly
    $stmt2->execute();
    require 'transcribe_video.php';
} else {
    echo json_encode(['status' => 'error', 'message' => 'Failed to save video data: ' . $stmt->error]); // Added stmt->error for debugging
}

$stmt->close();
// $stmt2->close();
$conn->close();

?>