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

include_once 'db_connect.php';

$method = $_SERVER['REQUEST_METHOD'];

// 1. GET: Fetch all news for the table
if ($method == 'GET') {
    $query = "SELECT * FROM news ORDER BY date DESC";
    $result = $conn->query($query);
    
    $news = [];
    while($row = $result->fetch_assoc()) {
        $news[] = $row;
    }
    echo json_encode(["success" => true, "data" => $news]);
}

// 2. POST: Create or Update News (With Image Cleanup on Update)
if ($method == 'POST') {
    $data = json_decode(file_get_contents("php://input"));
    
    if (!empty($data->title) && !empty($data->category)) {
        $title = mysqli_real_escape_string($conn, $data->title);
        $category = mysqli_real_escape_string($conn, $data->category);
        $author = mysqli_real_escape_string($conn, $data->author);
        $date = mysqli_real_escape_string($conn, $data->date);
        $excerpt = mysqli_real_escape_string($conn, $data->excerpt);
        $content = mysqli_real_escape_string($conn, $data->content);
        $image_url = mysqli_real_escape_string($conn, $data->image_url);

        if (isset($data->id) && $data->id > 0) {
            // UPDATE LOGIC
            $id = intval($data->id);

            // A. Check for existing image to see if we need to swap/delete it
            $stmt = $conn->prepare("SELECT image_url FROM news WHERE id = ?");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $res = $stmt->get_result();
            $old_article = $res->fetch_assoc();

            // B. If the new image URL is different from the old one, delete the old file
            if ($old_article && !empty($old_article['image_url']) && $old_article['image_url'] !== $image_url) {
                $old_file_path = ".." . $old_article['image_url'];
                if (file_exists($old_file_path)) {
                    unlink($old_file_path);
                }
            }

            $query = "UPDATE news SET 
                        title='$title', category='$category', author='$author', 
                        date='$date', excerpt='$excerpt', content='$content', 
                        image_url='$image_url' 
                      WHERE id=$id";
        } else {
            // INSERT LOGIC
            $query = "INSERT INTO news (title, category, author, date, excerpt, content, image_url) 
                      VALUES ('$title', '$category', '$author', '$date', '$excerpt', '$content', '$image_url')";
        }

        if ($conn->query($query)) {
            echo json_encode(["success" => true, "message" => "News saved and server storage cleaned."]);
        } else {
            http_response_code(500);
            echo json_encode(["success" => false, "message" => "Database error: " . $conn->error]);
        }
    }
}

// 3. DELETE: Remove News & Physically Delete Associated Image
if ($method == 'DELETE') {
    $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    
    if ($id > 0) {
        $stmt = $conn->prepare("SELECT image_url FROM news WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $res = $stmt->get_result();
        $article = $res->fetch_assoc();

        if ($article && !empty($article['image_url'])) {
            $file_path = ".." . $article['image_url']; 
            if (file_exists($file_path)) {
                unlink($file_path);
            }
        }

        $query = "DELETE FROM news WHERE id = $id";
        if ($conn->query($query)) {
            echo json_encode(["success" => true, "message" => "Article and associated image deleted."]);
        } else {
            http_response_code(500);
            echo json_encode(["success" => false, "message" => "Database error: " . $conn->error]);
        }
    } else {
        echo json_encode(["success" => false, "message" => "Invalid ID provided."]);
    }
}

$conn->close();
?>