<?php
session_start();
include('db_connection.php');

// Check if the student is logged in
if (!isset($_SESSION['student_id'])) {
    header("Location: login.php");
    exit();
}

$student_id = $_SESSION['student_id'];

// Check if request_id is set
if (!isset($_POST['request_id'])) {
    header("Location: friend_requests.php");
    exit();
}

$request_id = $_POST['request_id'];

// Fetch the sender_id from the friend request
$sql_fetch_sender = "SELECT student_id FROM student_requests WHERE request_id = ? AND requested_id = ? AND status = 'Pending'";
$stmt_fetch_sender = $conn->prepare($sql_fetch_sender);
$stmt_fetch_sender->bind_param("ii", $request_id, $student_id);
$stmt_fetch_sender->execute();
$result_sender = $stmt_fetch_sender->get_result();

if ($result_sender->num_rows > 0) {
    $row_sender = $result_sender->fetch_assoc();
    $sender_id = $row_sender['student_id'];

    // Start a transaction
    $conn->begin_transaction();

    try {
        // Update the friend request status to accepted
        $sql_accept_request = "UPDATE student_requests SET status = 'Accepted' WHERE request_id = ?";
        $stmt_accept_request = $conn->prepare($sql_accept_request);
        $stmt_accept_request->bind_param("i", $request_id);
        $stmt_accept_request->execute();

        // Insert the friend relationship into the student_friends table
        $sql_add_friend = "INSERT INTO student_friends (student_id, friend_id, status) VALUES (?, ?, 'Active'), (?, ?, 'Active')";
        $stmt_add_friend = $conn->prepare($sql_add_friend);
        $stmt_add_friend->bind_param("iiii", $student_id, $sender_id, $sender_id, $student_id);
        $stmt_add_friend->execute();

        // Commit the transaction
        $conn->commit();

        echo "Friend request accepted and friend added.";
    } catch (Exception $e) {
        // Rollback the transaction if any query fails
        $conn->rollback();
        echo "Error: " . $e->getMessage();
    }

} else {
    echo "Invalid friend request.";
}

$conn->close();
header("Location: friends.php");
exit();
?>
