<?php
// File: /admin/article_handler.php
session_start();
include '../db.php'; // Adjust path if needed

// Enable error reporting to catch issues
ini_set('display_errors', 1);
error_reporting(E_ALL);

// --- FUNCTION TO HANDLE FILE UPLOAD ---
function uploadImage($fileInputName) {
    $target_dir = "../uploads/articles/"; // Ensure this folder exists
    if (!is_dir($target_dir)) {
        mkdir($target_dir, 0777, true);
    }

    if (isset($_FILES[$fileInputName]) && $_FILES[$fileInputName]['error'] == 0) {
        $file_extension = pathinfo($_FILES[$fileInputName]["name"], PATHINFO_EXTENSION);
        $new_filename = uniqid() . "." . $file_extension;
        $target_file = $target_dir . $new_filename;
        
        // Allow only certain file formats
        $allowed_types = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        if (!in_array(strtolower($file_extension), $allowed_types)) {
            return ['error' => 'Invalid file type.'];
        }

        if (move_uploaded_file($_FILES[$fileInputName]["tmp_name"], $target_file)) {
            // Return path relative to root (remove '../')
            return ['path' => "uploads/articles/" . $new_filename]; 
        } else {
            return ['error' => 'Failed to move uploaded file.'];
        }
    }
    return ['path' => null]; // No file uploaded
}

// ========================================================
// 1. HANDLE ADD NEW ARTICLE
// ========================================================
if (isset($_POST['add_article'])) {
    $title = trim($_POST['title']);
    $category = $_POST['category'];
    $content = trim($_POST['content']);
    $video_url = trim($_POST['video_url'] ?? ''); // NEW: Get Video URL

    // Upload Image
    $upload = uploadImage('featured_image');
    if (isset($upload['error'])) {
        die("Error: " . $upload['error']);
    }
    $image_path = $upload['path'] ?? ''; // Default to empty if no image

    // INSERT Query (Updated to include video_url)
    $stmt = $conn->prepare("INSERT INTO articles (title, category, content, image_path, video_url) VALUES (?, ?, ?, ?, ?)");
    $stmt->bind_param("sssss", $title, $category, $content, $image_path, $video_url);

    if ($stmt->execute()) {
        header("Location: articles.php?status=success");
        exit();
    } else {
        die("Database Error: " . $stmt->error);
    }
}

// ========================================================
// 2. HANDLE EDIT ARTICLE
// ========================================================
if (isset($_POST['edit_article'])) {
    $id = filter_var($_POST['article_id'], FILTER_SANITIZE_NUMBER_INT);
    $title = trim($_POST['title']);
    $category = $_POST['category'];
    $content = trim($_POST['content']);
    $existing_image = $_POST['existing_image_path'];
    $video_url = trim($_POST['video_url'] ?? ''); // NEW: Get Video URL

    // Check for new image upload
    $image_path = $existing_image;
    if (!empty($_FILES['featured_image']['name'])) {
        $upload = uploadImage('featured_image');
        if (isset($upload['error'])) {
            die("Error: " . $upload['error']);
        }
        $image_path = $upload['path'];
    }

    // UPDATE Query (Updated to include video_url)
    $stmt = $conn->prepare("UPDATE articles SET title=?, category=?, content=?, image_path=?, video_url=? WHERE id=?");
    $stmt->bind_param("sssssi", $title, $category, $content, $image_path, $video_url, $id);

    if ($stmt->execute()) {
        header("Location: articles.php?status=updated");
        exit();
    } else {
        die("Database Error: " . $stmt->error);
    }
}

// ========================================================
// 3. HANDLE DELETE ARTICLE
// ========================================================
if (isset($_POST['delete_article'])) {
    $id = filter_var($_POST['article_id'], FILTER_SANITIZE_NUMBER_INT);

    // Optional: Delete the image file from server
    /*
    $img_stmt = $conn->prepare("SELECT image_path FROM articles WHERE id = ?");
    $img_stmt->bind_param("i", $id);
    $img_stmt->execute();
    $res = $img_stmt->get_result();
    if ($row = $res->fetch_assoc()) {
        if (file_exists("../" . $row['image_path'])) {
            unlink("../" . $row['image_path']);
        }
    }
    */

    $stmt = $conn->prepare("DELETE FROM articles WHERE id = ?");
    $stmt->bind_param("i", $id);

    if ($stmt->execute()) {
        header("Location: articles.php?status=deleted");
        exit();
    } else {
        die("Database Error: " . $stmt->error);
    }
}
?>