<?php
session_start();
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
header('Content-Type: application/json; charset=utf-8');

include 'db/config.php';

// Helper function to sanitize input
function check_input($par) {
    return htmlspecialchars(stripslashes(trim($par)));
}

// Validate parameters
if (empty($_POST['user_id']) || empty($_POST['auth']) || empty($_POST['match_id'])) {
    echo json_encode(['status' => false, 'success' => 'Missing required parameters']);
    exit;
}

$user_id  = check_input($_POST['user_id']);
$auth     = check_input($_POST['auth']);
$match_id = check_input($_POST['match_id']);
$date_t   = date("Y-m-d H:i:s");

// Prevent self-like
if ($user_id === $match_id) {
    echo json_encode(['status' => false, 'success' => 'You cannot like yourself']);
    exit;
}

// Authenticate user
$stmt = $con->prepare("SELECT * FROM users WHERE user_id = ? AND auth = ?");
$stmt->bind_param("ss", $user_id, $auth);
$stmt->execute();
$userRes = $stmt->get_result();

if ($userRes->num_rows !== 1) {
    echo json_encode(['status' => false, 'success' => 'Invalid user ID or authentication token']);
    exit;
}

// Get liker profile
$userData = $userRes->fetch_assoc();
$firstname     = $userData['firstname'];
$lastname     = $userData['lastname'];

$name     = $firstname." ".$lastname;
$img      = $userData['img'];
$city     = $userData['city'];
$state    = $userData['state'];
$country  = $userData['country'];

// Get liked profile
$stmt = $con->prepare("SELECT * FROM users WHERE user_id = ?");
$stmt->bind_param("s", $match_id);
$stmt->execute();
$matchRes = $stmt->get_result();

if ($matchRes->num_rows !== 1) {
    echo json_encode(['status' => false, 'success' => 'Matched user not found']);
    exit;
}

$matchData = $matchRes->fetch_assoc();

$firstname2     = $matchData['firstname'];
$lastname2     =  $matchData['lastname'];

$name2     = $firstname2." ".$lastname2;
$img2      = $matchData['img'];
$city1     = $matchData['city'];
$state1    = $matchData['state'];
$country1  = $matchData['country'];

// Check if already liked
$stmt = $con->prepare("SELECT id FROM likes WHERE user_id = ? AND match_id = ?");
$stmt->bind_param("ss", $user_id, $match_id);
$stmt->execute();
$likeCheck = $stmt->get_result();

if ($likeCheck->num_rows > 0) {
    echo json_encode(['status' => false, 'success' => 'You already liked this user']);
    exit;
}

$con->begin_transaction();

try {
    // Add like
    $stmt = $con->prepare("INSERT INTO likes (user_id, match_id, type, name, img, city, state, country, date_t) VALUES (?, ?, 'Like',  ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("ssssssss", $user_id, $match_id, $name2, $img2, $city1, $state1, $country1, $date_t);
    $stmt->execute();


 $stmt = $con->prepare("INSERT INTO likes_me (user_id, type, match_id, name, img, city, state, country, date_t) VALUES (?, 'Super Like', ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("ssssssss", $match_id, $user_id, $name, $img, $city, $state, $country, $date_t);
    $stmt->execute();



    // Check for mutual like
    $stmt = $con->prepare("SELECT id FROM likes WHERE user_id = ? AND match_id = ?");
    $stmt->bind_param("ss", $match_id, $user_id);
    $stmt->execute();
    $mutualRes = $stmt->get_result();

    if ($mutualRes->num_rows > 0) {
        // Insert into matches for both users
        $matchStmt = $con->prepare("
            INSERT INTO matches (user_id, match_id, name, img, city, state, country, date_t)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ");
        // For user 1
        $matchStmt->bind_param("ssssssss", $user_id, $match_id, $name2, $img2, $city1, $state1, $country1, $date_t);
        $matchStmt->execute();
        // For user 2
        $matchStmt->bind_param("ssssssss", $match_id, $user_id, $name, $img, $city, $state, $country, $date_t);
        $matchStmt->execute();

        // Add to activities
        $details1 = "You and {$name2} are now a match!";
        $details2 = "You and {$name} are now a match!";

        $actStmt = $con->prepare("INSERT INTO activities (user_id, title, img, details, date_t) VALUES (?, 'Match', ?, ?, ?)");
        $actStmt->bind_param("ssss", $user_id, $img2, $details1, $date_t);
        $actStmt->execute();

        $actStmt->bind_param("ssss", $match_id, $img, $details2, $date_t);
        $actStmt->execute();

        $con->commit();
        echo json_encode(['status' => true, 'success' => "It's a Match" ]);
        exit;
    }

    $con->commit();
    echo json_encode(['status' => true, 'success' => 'Liked']);

} catch (Exception $e) {
    $con->rollback();
    echo json_encode(['status' => false, 'success' => 'Error: ' . $e->getMessage()]);
}

$con->close();
?>
