<?php

include_once __DIR__ . '/../secrets.php';
header('Content-Type: application/json; charset=utf-8');
include '../db_connect.php';

$json = file_get_contents('php://input');
$data = json_decode($json, true);

$userid = $data['userid'];
$key = $data['key'];

$security_key = decrypData($key);
$response = array();

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

if ($security_key == SECURITY_KEY_PLAIN) {

    $con = dbConnect();
    $storyUrl   = 'https://app.bpluspro.xyz/social/story/';
    $profileurl = 'https://app.bpluspro.xyz/social/';
    $storyFolder = __DIR__ . "/../../social/story/";

    /* -----------------------------------------------
        Auto Delete All Stories Older Than 24 Hours
    ----------------------------------------------- */

    $currentTime = round(microtime(true) * 1000);
    $expireLimit = 24 * 60 * 60 * 1000;

    $deleteSql = "SELECT id, image, time FROM story_table";
    $deleteResult = mysqli_query($con, $deleteSql);

    while ($story = mysqli_fetch_assoc($deleteResult)) {
        $storyTime = intval($story['time']);

        if ($currentTime - $storyTime >= $expireLimit) {
            $filePath = $storyFolder . $story['image'];
            if (file_exists($filePath)) {
                unlink($filePath);
            }
            mysqli_query($con, "DELETE FROM story_table WHERE id = '{$story['id']}'");
        }
    }

    /* -----------------------------------------------
       1️⃣ Find all accepted friends of logged in user
    ----------------------------------------------- */

    $friendList = [];

    $sqlFriends = "
        SELECT 
            CASE 
                WHEN sender_id = ? THEN receiver_id
                WHEN receiver_id = ? THEN sender_id
            END AS friend_id
        FROM friends_request
        WHERE 
            (sender_id = ? OR receiver_id = ?)
            AND status = 'accepted'
    ";

    $stmt = $con->prepare($sqlFriends);
    if ($stmt) {
        $stmt->bind_param("ssss", $userid, $userid, $userid, $userid);
        $stmt->execute();
        $result = $stmt->get_result();
        
        while ($fr = $result->fetch_assoc()) {
            if (!empty($fr['friend_id'])) {
                $friendList[] = $fr['friend_id'];
            }
        }
        $stmt->close();
    }

    // Debug log (আপনার server error log এ দেখতে পারেন)
    error_log("User ID: $userid");
    error_log("Friends count: " . count($friendList));
    error_log("Friends list: " . implode(', ', $friendList));

    /* -----------------------------------------------
       2️⃣ সব story পাওয়ার জন্য query (প্রথমে নিজের, তারপর friends, তারপর অন্যান্য)
    ----------------------------------------------- */

    // সব user যাদের story দেখাতে চাই (নিজের + friends)
    $allUsersToShow = array_merge([$userid], $friendList);
    
    $storyArray = array();
    
    if (!empty($allUsersToShow)) {
        $placeholders = implode(',', array_fill(0, count($allUsersToShow), '?'));
        
        $storySql = "
            SELECT 
                st.id,
                st.userid,
                st.image,
                st.time,
                CASE
                    WHEN LENGTH(st.userid) = 8 THEN su.name
                    WHEN LENGTH(st.userid) = 9 THEN pt.name
                    ELSE 'Unknown'
                END AS username,
                CASE
                    WHEN LENGTH(st.userid) = 8 THEN su.image
                    WHEN LENGTH(st.userid) = 9 THEN pt.image
                    ELSE ''
                END AS userimage,
                CASE
                    WHEN LENGTH(st.userid) = 8 THEN su.bpay
                    WHEN LENGTH(st.userid) = 9 THEN pt.bpay
                    ELSE ''
                END AS bpay,
                CASE
                    WHEN st.userid = ? THEN 1  -- Priority 1: নিজের story
                    ELSE 2  -- Priority 2: friends এর story
                END AS priority
            FROM story_table st
            LEFT JOIN signup su 
                ON LENGTH(st.userid) = 8 AND st.userid = su.userid
            LEFT JOIN page_table pt
                ON LENGTH(st.userid) = 9 AND st.userid = pt.userid
            WHERE st.userid IN ($placeholders)
            ORDER BY priority ASC, st.time DESC
            LIMIT 100  -- আপনি প্রয়োজন অনুযায়ী limit বাড়াতে পারেন
        ";
        
        $stmt2 = $con->prepare($storySql);
        if ($stmt2) {
            // Parameters প্রস্তুত করুন: প্রথমে $userid (যেটি CASE WHEN এ আছে), তারপর সব user IDs
            $params = array_merge([$userid], $allUsersToShow);
            $types = str_repeat('s', count($params));
            
            $stmt2->bind_param($types, ...$params);
            $stmt2->execute();
            $storyResult = $stmt2->get_result();
            
            while ($item = $storyResult->fetch_assoc()) {
                $storyArray[] = array(
                    'id'        => $item['id'],
                    'userid'    => $item['userid'],
                    'image'     => $storyUrl . $item['image'],
                    'time'      => $item['time'],
                    'username'  => $item['username'],
                    'userimage' => !empty($item['userimage']) ? $profileurl . $item['userimage'] : '',
                    'bpay'      => $item['bpay'],
                    'priority'  => $item['priority']  // debug করার জন্য
                );
            }
            $stmt2->close();
            
            error_log("Total stories found: " . count($storyArray));
            
        } else {
            error_log("Story query preparation failed: " . $con->error);
        }
    }

    // যদি কোন story না থাকে, তাহলে শুধু নিজের story দেখানোর চেষ্টা করুন
    if (empty($storyArray)) {
        $selfStorySql = "
            SELECT 
                st.id,
                st.userid,
                st.image,
                st.time,
                CASE
                    WHEN LENGTH(st.userid) = 8 THEN su.name
                    WHEN LENGTH(st.userid) = 9 THEN pt.name
                    ELSE 'Unknown'
                END AS username,
                CASE
                    WHEN LENGTH(st.userid) = 8 THEN su.image
                    WHEN LENGTH(st.userid) = 9 THEN pt.image
                    ELSE ''
                END AS userimage,
                CASE
                    WHEN LENGTH(st.userid) = 8 THEN su.bpay
                    WHEN LENGTH(st.userid) = 9 THEN pt.bpay
                    ELSE ''
                END AS bpay
            FROM story_table st
            LEFT JOIN signup su 
                ON LENGTH(st.userid) = 8 AND st.userid = su.userid
            LEFT JOIN page_table pt
                ON LENGTH(st.userid) = 9 AND st.userid = pt.userid
            WHERE st.userid = ?
            ORDER BY st.time DESC
        ";
        
        $stmt3 = $con->prepare($selfStorySql);
        if ($stmt3) {
            $stmt3->bind_param("s", $userid);
            $stmt3->execute();
            $selfResult = $stmt3->get_result();
            
            while ($item = $selfResult->fetch_assoc()) {
                $storyArray[] = array(
                    'id'        => $item['id'],
                    'userid'    => $item['userid'],
                    'image'     => $storyUrl . $item['image'],
                    'time'      => $item['time'],
                    'username'  => $item['username'],
                    'userimage' => $profileurl . $item['userimage'],
                    'bpay'      => $item['bpay']
                );
            }
            $stmt3->close();
        }
    }

    $response = array(
        'story' => $storyArray,
        'total_stories' => count($storyArray),
        'total_friends' => count($friendList),
        'user_id' => $userid
    );
    
    echo json_encode($response, JSON_UNESCAPED_SLASHES);

    $con->close();
}

?>