<?php

require_once "config.php";

header('Content-Type: application/json');

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'GET':
        $cusename = $_GET['cusername'] ?? '';
        $query = $conn->prepare("SELECT ckode, nlike FROM tblike WHERE cusername = ?");
        $query->bind_param("s", $cusename);
        $query->execute();
        $result = $query->get_result();
        $data = $result->fetch_all(MYSQLI_ASSOC);
        echo json_encode($data);
        break;

    case 'POST':
        $input = json_decode(file_get_contents("php://input"), true);
        
        $ckode = $input['ckode'] ?? '';
        $nlike = $input['nlike'] ?? 0;
        $cusename = $input['cusername'] ?? '';

        if ($ckode && $cusename) {
            $query = $conn->prepare("INSERT INTO tblike (ckode, nlike, cusername) VALUES (?, ?, ?)");
            $query->bind_param("sis", $ckode, $nlike, $cusename);

            if ($query->execute()) {
                echo json_encode(["message" => "Record inserted successfully"]);
            } else {
                echo json_encode(["message" => "Error inserting record"]);
            }
        } else {
            echo json_encode(["message" => "Invalid input"]);
        }
        break;
        case 'DELETE':
            parse_str(file_get_contents("php://input"), $input); // Retrieve the input
            $ckode = $input['ckode'] ?? '';
            $cusename = $input['cusername'] ?? '';
        
            if ($ckode && $cusename) {
                $query = $conn->prepare("DELETE FROM tblike WHERE ckode = ? AND cusername = ?");
                $query->bind_param("ss", $ckode, $cusename);
        
                if ($query->execute()) {
                    echo json_encode(["message" => "Record deleted successfully"]);
                } else {
                    echo json_encode(["message" => "Error deleting record"]);
                }
            } else {
                echo json_encode(["message" => "Invalid input"]);
            }
            break;


}

mysqli_close($conn);
?>
