<?php

include_once __DIR__ . '/../secrets.php';
include '../db_connect.php'; 

$userid = $_POST['userid'];
$image = $_POST['image'];
$time = $_POST['time'];
$key = $_POST['key'];

$security_key = decrypData($key);

if ($security_key === false) {
    echo json_encode(['error' => 'Invalid encryption data']);
    exit;
}

if ($security_key == SECURITY_KEY_PLAIN) {

    $con = dbConnect();

    // 🔥 1. Check if this user already has a story
    $checkSql = "SELECT id FROM story_table WHERE userid = '$userid'";
    $checkResult = mysqli_query($con, $checkSql);

    if (mysqli_num_rows($checkResult) > 0) {
        echo json_encode(['error' => 'Story already exists for this user']);
        exit;
    }

    // 🔥 2. If no story exists — upload new story
    $decodedimage = base64_decode($image);
    $fileName = time().'_' . rand(1000, 10000) . '.jpg';
    $filePath = 'images/'. $fileName;

    if (file_put_contents($filePath, $decodedimage)) {

        $sql = "INSERT INTO story_table(userid,image, time) VALUES ('$userid','$filePath','$time')";
        $result = mysqli_query($con, $sql);

        if ($result) {
            echo json_encode(['success' => 'Story uploaded']);
        } else {
            echo json_encode(['error' => 'Database insert failed']);
        }

    } else {
        echo json_encode(['error' => 'Image upload failed']);
    }
}

?>
