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

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

// Get POST data
$data = json_decode(file_get_contents('php://input'), true);
$user_id = $_SESSION['user_id'];
$course_id = intval($data['course_id'] ?? 0);
$image_data = $data['image_data'] ?? '';

if (!$course_id || !$image_data) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid input']);
    exit;
}

// Check if certificate already exists
$stmt = $conn->prepare("SELECT id FROM certificates WHERE user_id=? AND course_id=?");
$stmt->bind_param("ii", $user_id, $course_id);
$stmt->execute();
if($stmt->get_result()->num_rows > 0){
    echo json_encode(['status' => 'error', 'message' => 'Certificate already exists']);
    exit;
}

// Decode base64 image
$img = str_replace('data:image/png;base64,', '', $image_data);
$img = str_replace(' ', '+', $img);
$image_binary = base64_decode($img);

// Create folder if not exists
$folder = "certificates";
if(!is_dir($folder)){
    mkdir($folder, 0755, true);
}

// Save file
$filename = $folder . "/certificate_{$user_id}_{$course_id}_" . time() . ".png";
file_put_contents($filename, $image_binary);

// Insert into database
$stmt = $conn->prepare("INSERT INTO certificates (user_id, course_id, image_path) VALUES (?, ?, ?)");
$stmt->bind_param("iis", $user_id, $course_id, $filename);
if($stmt->execute()){
    echo json_encode(['status' => 'success', 'image_path' => $filename]);
} else {
    echo json_encode(['status' => 'error', 'message' => 'Database error']);
}
