<?php
session_start();
include '../database/db.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: ../users/login.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$error_message = "";
$success_message = "";

// Drauga noņemšana
if (isset($_GET['unfriend'])) {
    $unfriend_id = (int)$_GET['unfriend'];
    $stmt = $pdo->prepare("
        DELETE FROM friends 
        WHERE (user_id = ? AND friend_id = ?) 
           OR (user_id = ? AND friend_id = ?)
    ");
    $stmt->execute([$user_id, $unfriend_id, $unfriend_id, $user_id]);
    header("Location: add_friend.php?unfriended=1");
    exit();
}

// Pieprasījuma apstiprināšana
if (isset($_GET['accept'])) {
    $friend_row_id = (int)$_GET['accept'];
    $stmt = $pdo->prepare("
        UPDATE friends SET status = 'accepted' 
        WHERE id = ? AND friend_id = ?
    ");
    $stmt->execute([$friend_row_id, $user_id]);
    header("Location: add_friend.php?accepted=1");
    exit();
}

// Pieprasījuma noraidīšana
if (isset($_GET['decline'])) {
    $friend_row_id = (int)$_GET['decline'];
    $stmt = $pdo->prepare("
        DELETE FROM friends 
        WHERE id = ? AND friend_id = ?
    ");
    $stmt->execute([$friend_row_id, $user_id]);
    header("Location: add_friend.php?declined=1");
    exit();
}

// Drauga pievienošana
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['friend_email'])) {
    $friend_email = $_POST['friend_email'];

    $stmt = $pdo->prepare("SELECT id, name FROM users WHERE email = ?");
    $stmt->execute([$friend_email]);
    $friend = $stmt->fetch();

    if ($friend) {
        $friend_id = $friend['id'];
        
        if ($friend_id == $user_id) {
            $error_message = "You cannot add yourself as a friend!";
        } else {
            // Vai jau eksistē jebkādā virzienā
            $stmt = $pdo->prepare("
                SELECT * FROM friends 
                WHERE (user_id = ? AND friend_id = ?) 
                   OR (user_id = ? AND friend_id = ?)
            ");
            $stmt->execute([$user_id, $friend_id, $friend_id, $user_id]);

            if ($stmt->rowCount() > 0) {
                $error_message = "Friend request already sent or you are already friends!";
            } else {
                // Sūtām pieprasījumu ar status = 'pending'
                $stmt = $pdo->prepare("
                    INSERT INTO friends (user_id, friend_id, status) VALUES (?, ?, 'pending')
                ");
                $stmt->execute([$user_id, $friend_id]);
                $success_message = "Friend request sent!";
            }
        }
    } else {
        $error_message = "User with this e-mail was not found.";
    }
}

// Apstiprināti draugi (abas puses accepted VAI viens nosūtīja un otrs apstiprināja)
$friends_stmt = $pdo->prepare("
    SELECT DISTINCT u.id, u.name, u.email 
    FROM users u
    WHERE u.id IN (
        SELECT friend_id FROM friends 
        WHERE user_id = ? AND status = 'accepted'
        UNION
        SELECT user_id FROM friends 
        WHERE friend_id = ? AND status = 'accepted'
    )
    AND u.id != ?
    ORDER BY u.name ASC
");
$friends_stmt->execute([$user_id, $user_id, $user_id]);
$friends_list = $friends_stmt->fetchAll(PDO::FETCH_ASSOC);

// Ienākošie pieprasījumi
$incoming_stmt = $pdo->prepare("
    SELECT f.id, u.name, u.email
    FROM friends f
    JOIN users u ON f.user_id = u.id
    WHERE f.friend_id = ? AND f.status = 'pending'
");
$incoming_stmt->execute([$user_id]);
$incoming_requests = $incoming_stmt->fetchAll(PDO::FETCH_ASSOC);

// Nosūtītie pieprasījumi
$sent_stmt = $pdo->prepare("
    SELECT f.id, u.name, u.email
    FROM friends f
    JOIN users u ON f.friend_id = u.id
    WHERE f.user_id = ? AND f.status = 'pending'
");
$sent_stmt->execute([$user_id]);
$sent_requests = $sent_stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Friends - Work Planner</title>
    <link rel="stylesheet" href="../css/style.css">
    <link rel="stylesheet" href="../css/add_friend.css">
</head>
<body>
<nav>
    <ul>
        <li><a href="../dashboard.php">Dashboard</a></li>
        <li><a href="../calendar/calendar.php">Calendar</a></li>
        <li><a href="../tasks/tasks.php">All Tasks</a></li>
        <li><a href="../teams/teams.php">Teams</a></li>
        <li><a href="../friends/add_friend.php">Friends</a></li>
        <li><a href="../profile/profile.php">Profile</a></li>
        <li><a href="../users/logout.php">Logout</a></li>
    </ul>
</nav>

<main>
    <h2>Friends</h2>
    
    <div class="friends-page-container">
        <div class="add-friend-section">
            <h3>Add New Friend</h3>
            
            <?php if (!empty($error_message)): ?>
                <div class="message-box error"><?= htmlspecialchars($error_message) ?></div>
            <?php endif; ?>
            <?php if (!empty($success_message)): ?>
                <div class="message-box success"><?= htmlspecialchars($success_message) ?></div>
            <?php endif; ?>
            <?php if (isset($_GET['unfriended'])): ?>
                <div class="message-box success">Friend removed successfully!</div>
            <?php endif; ?>
            <?php if (isset($_GET['accepted'])): ?>
                <div class="message-box success">Friend request accepted!</div>
            <?php endif; ?>
            <?php if (isset($_GET['declined'])): ?>
                <div class="message-box success">Friend request declined.</div>
            <?php endif; ?>
            
            <form method="post" class="friend-form">
                <div class="form-group">
                    <label for="friend_email">Friend's E-mail</label>
                    <input type="email" name="friend_email" id="friend_email" required 
                           placeholder="Enter friend's email address">
                </div>
                <button type="submit" class="btn-add-friend">Send Friend Request</button>
            </form>
        </div>

        <!-- Ienākošie pieprasījumi -->
        <?php if (count($incoming_requests) > 0): ?>
        <div class="friends-list-section">
            <h3>Incoming Friend Requests (<?= count($incoming_requests) ?>)</h3>
            <div class="friends-grid">
                <?php foreach ($incoming_requests as $req): ?>
                    <div class="friend-card pending">
                        <div class="friend-info">
                            <div class="friend-name"><?= htmlspecialchars($req['name']) ?></div>
                            <div class="friend-email"><?= htmlspecialchars($req['email']) ?></div>
                        </div>
                        <div class="request-actions">
                            <a href="?accept=<?= $req['id'] ?>" class="btn-accept">Accept</a>
                            <a href="?decline=<?= $req['id'] ?>" class="btn-decline">Decline</a>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- Nosūtītie pieprasījumi -->
        <?php if (count($sent_requests) > 0): ?>
        <div class="friends-list-section">
            <h3>Sent Requests (<?= count($sent_requests) ?>)</h3>
            <div class="friends-grid">
                <?php foreach ($sent_requests as $req): ?>
                    <div class="friend-card sent">
                        <div class="friend-info">
                            <div class="friend-name"><?= htmlspecialchars($req['name']) ?></div>
                            <div class="friend-email"><?= htmlspecialchars($req['email']) ?></div>
                        </div>
                        <span class="badge-pending">Pending...</span>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- Draugi -->
        <div class="friends-list-section">
            <h3>Your Friends (<?= count($friends_list) ?>)</h3>
            <?php if (count($friends_list) > 0): ?>
                <div class="friends-grid">
                    <?php foreach ($friends_list as $friend): ?>
                        <div class="friend-card">
                            <div class="friend-info">
                                <div class="friend-name"><?= htmlspecialchars($friend['name']) ?></div>
                                <div class="friend-email"><?= htmlspecialchars($friend['email']) ?></div>
                            </div>
                            <a href="?unfriend=<?= $friend['id'] ?>" 
                               class="btn-unfriend"
                               onclick="return confirm('Remove <?= htmlspecialchars($friend['name']) ?> from your friends?');">
                               Unfriend
                            </a>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <div class="empty-state">
                    <p>You haven't added any friends yet.</p>
                </div>
            <?php endif; ?>
        </div>

        <a href="../dashboard.php" class="back-link">← Back to Dashboard</a>
    </div>
</main>
</body>
</html>