<?php
session_start();
include("connect.php");

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo "<script>alert('Session expired. Please log in again.'); window.location.href='login.php';</script>";
    exit;
}

$userid = $_SESSION['user_id'];

// Handle POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Sanitize and validate inputs
    $doctorname = trim($_POST['doctorname'] ?? '');
    $form_upload  = basename(filter_var($_POST['uploaded_form_file'] ?? '', FILTER_SANITIZE_STRING));
    $photo_upload = basename(filter_var($_POST['uploaded_photo_file'] ?? '', FILTER_SANITIZE_STRING));
    $video_upload = basename(filter_var($_POST['uploaded_video_file'] ?? '', FILTER_SANITIZE_STRING));

    $approval_status = '';
    $approval_by = '';

    // Check required fields
    if (empty($doctorname)) {
        echo "<script>alert('Doctor name is required.'); history.back();</script>";
        exit;
    }

    if (!$form_upload && !$photo_upload && !$video_upload) {
        echo "<script>alert('Please upload at least one file.'); history.back();</script>";
        exit;
    }

    // Prepare SQL query
    $sql = "INSERT INTO camp_upload (
        userid, doctor_name, form_upload, photo_upload, video_upload, approval_status, approval_by
    ) VALUES (?, ?, ?, ?, ?, ?, ?)";

    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("sssssss", 
            $userid, 
            $doctorname, 
            $form_upload, 
            $photo_upload, 
            $video_upload, 
            $approval_status, 
            $approval_by
        );

        if ($stmt->execute()) {
            echo "<script>alert('Upload information saved successfully.'); window.location.href='thank-you.php';</script>";
        } else {
            echo "<script>alert('Failed to save upload information. Please try again.'); window.location.href='form-dashboard.php';</script>";
        }

        $stmt->close();
    } else {
        echo "<script>alert('Database error. Please try again later.'); history.back();</script>";
    }
}

$conn->close();
?>
