<?php
// announcements_api.php
// GET -> return JSON list of announcements
// POST -> create announcement (admin only)

if (session_status() == PHP_SESSION_NONE) session_start();
require_once 'main_db_connect.php'; // uses $conn -> ppdconline_ppdco

// Configuration: canonical host (public URL) and filesystem path for the shared uploads directory.
// Set $FILE_HOST to the main domain that serves the files (include scheme, no trailing slash)
// and $UPLOAD_FS_PATH to the absolute filesystem path to that domain's public_html/uploads/bulletins/ directory.
// Example values - change these to match your cPanel account and domain.
$FILE_HOST = 'https://lagunappdco.online';
$UPLOAD_WEB_SUBDIR = '/uploads/bulletins/';
$UPLOAD_FS_PATH = '/home/ppdconline/public_html' . $UPLOAD_WEB_SUBDIR; // absolute filesystem path

// Helper: produce a full URL the browser can fetch for a stored attachment value
function attachment_to_url($attachment, $fileHost) {
    if (!$attachment) return null;
    // If already a full URL, return as-is
    if (preg_match('#^https?://#i', $attachment)) return $attachment;
    $a = str_replace('\\', '/', $attachment);
    // If it contains 'public_html/', use the part after it
    if (strpos($a, 'public_html/') !== false) {
        $p = substr($a, strpos($a, 'public_html/') + strlen('public_html/'));
        return rtrim($fileHost, '/') . '/' . ltrim($p, '/');
    }
    // If it already starts with '/uploads' or contains 'uploads/', use that segment
    if (strpos($a, '/uploads/') === 0) {
        return rtrim($fileHost, '/') . $a;
    }
    if (strpos($a, 'uploads/') !== false) {
        $p = substr($a, strpos($a, 'uploads/'));
        return rtrim($fileHost, '/') . '/' . ltrim($p, '/');
    }
    // If it's a relative path like 'uploads/..', prefix with host
    if (strpos($a, 'uploads/') === 0 || preg_match('#^uploads/#', $a)) {
        return rtrim($fileHost, '/') . '/' . ltrim($a, '/');
    }
    // As a last resort, if it's an absolute path under document root, strip docroot and prefix
    $docRoot = rtrim(@$_SERVER['DOCUMENT_ROOT'], '/\\');
    if ($docRoot && strpos($a, $docRoot) === 0) {
        $p = substr($a, strlen($docRoot));
        return $p ? rtrim($fileHost, '/') . '/' . ltrim($p, '/') : null;
    }
    return null;
}

// Resolve the full filesystem path for a stored attachment value.
// Uses the configured shared uploads path when possible.
function resolve_attachment_fullpath($attachment) {
    global $UPLOAD_FS_PATH;
    if (!$attachment) return null;
    // If it's already an absolute filesystem path, return it
    if (preg_match('#^(/|[A-Za-z]:\\\\|/home/)#', $attachment)) return $attachment;
    $a = str_replace('\\', '/', $attachment);
    // If path contains uploads/ just assume file is under the shared uploads dir
    if (strpos($a, 'uploads/') !== false) {
        // Use basename to avoid accidental path traversal
        $bn = basename($a);
        return rtrim($UPLOAD_FS_PATH, '/\\') . '/' . $bn;
    }
    // Fallback to document root + attachment
    $docRoot = rtrim(@$_SERVER['DOCUMENT_ROOT'], '/\\');
    return $docRoot . '/' . ltrim($a, '/\\');
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // Fetch announcements
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 50;
    $stmt = $conn->prepare("SELECT id, uploader_username, title, content, category, link, attachment, date_posted FROM announcements ORDER BY date_posted DESC LIMIT ?");
    $stmt->bind_param('i', $limit);
    $stmt->execute();
    $res = $stmt->get_result();
    $rows = [];
    while ($r = $res->fetch_assoc()) {
        // Add a browser-fetchable URL for attachments (absolute URL) using configured host
        $r['attachment_url'] = isset($r['attachment']) ? attachment_to_url($r['attachment'], $FILE_HOST) : null;
        $rows[] = $r;
    }
    echo json_encode(['success' => true, 'data' => $rows]);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Only allow admins to post announcements
    if (!isset($_SESSION['user_type']) || $_SESSION['user_type'] !== 'admin') {
        echo json_encode(['success' => false, 'error' => 'Unauthorized']);
        exit();
    }
    // Support actions: create (default), update, delete
    $action = $_POST['action'] ?? 'create';

    // Helper to handle file uploads and return relative attachment path or null
    $handleUpload = function() use ($UPLOAD_FS_PATH, $UPLOAD_WEB_SUBDIR) {
        if (empty($_FILES['attachment']) || $_FILES['attachment']['error'] !== UPLOAD_ERR_OK) return null;
        $docRoot = rtrim($_SERVER['DOCUMENT_ROOT'], '/\\');

        // Prefer the central shared uploads directory (absolute path). If not writable, fall back to docroot + web subdir.
        $uploadDir = rtrim($UPLOAD_FS_PATH, '/\\') . '/';
        if (!is_dir($uploadDir) && !@mkdir($uploadDir, 0755, true)) {
            // fallback to document root
            $uploadDir = $docRoot . $UPLOAD_WEB_SUBDIR;
            if (!is_dir($uploadDir)) @mkdir($uploadDir, 0755, true);
        }

        $origName = basename($_FILES['attachment']['name']);
        $ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
        $allowedExt = ['jpg','jpeg','png','gif','webp','pdf','doc','docx','xls','xlsx'];
        if (!in_array($ext, $allowedExt)) {
            return ['error' => 'File type not allowed'];
        }
        // Optional: enforce max size (e.g., 8MB)
        $maxBytes = 8 * 1024 * 1024;
        if ($_FILES['attachment']['size'] > $maxBytes) {
            return ['error' => 'File too large'];
        }
        $newName = uniqid('bulletin_', true) . '.' . $ext;
        $target = rtrim($uploadDir, '/\\') . '/' . $newName;
        if (move_uploaded_file($_FILES['attachment']['tmp_name'], $target)) {
            // store the web-relative path in DB (without leading slash) for portability
            $webPath = ltrim($UPLOAD_WEB_SUBDIR, '/') . $newName; // e.g. uploads/bulletins/....jpg
            return ['path' => $webPath];
        }
        return ['error' => 'Failed to move uploaded file'];
    };

    // CREATE
    if ($action === 'create') {
        $title = $_POST['title'] ?? '';
        $content = $_POST['content'] ?? '';
        $category = $_POST['category'] ?? 'Policy';
        $link = $_POST['link'] ?? null;
        $attachmentPath = null;

        if (!$title || !$content) {
            echo json_encode(['success' => false, 'error' => 'Title and content are required']);
            exit();
        }

        $uploadResult = $handleUpload();
        if (is_array($uploadResult) && isset($uploadResult['error'])) {
            echo json_encode(['success' => false, 'error' => $uploadResult['error']]);
            exit();
        }
        if (is_array($uploadResult) && isset($uploadResult['path'])) $attachmentPath = $uploadResult['path'];

        $uploader_username = $_SESSION['username'] ?? 'unknown';
        $stmt = $conn->prepare("INSERT INTO announcements (uploader_username, title, content, category, link, attachment) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->bind_param('ssssss', $uploader_username, $title, $content, $category, $link, $attachmentPath);
        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'id' => $stmt->insert_id]);
        } else {
            echo json_encode(['success' => false, 'error' => $conn->error]);
        }
        exit();
    }

    // DELETE
    if ($action === 'delete') {
        $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        if (!$id) { echo json_encode(['success' => false, 'error' => 'Missing id']); exit(); }
        // fetch attachment path to unlink
        $stmt = $conn->prepare("SELECT attachment FROM announcements WHERE id = ?");
        $stmt->bind_param('i', $id);
        $stmt->execute();
        $res = $stmt->get_result();
        $row = $res->fetch_assoc();
        if ($row) {
            $attachment = $row['attachment'];
            if ($attachment) {
                $full = resolve_attachment_fullpath($attachment);
                if ($full && file_exists($full)) @unlink($full);
            }
        }
        $del = $conn->prepare("DELETE FROM announcements WHERE id = ?");
        $del->bind_param('i', $id);
        if ($del->execute()) {
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'error' => $conn->error]);
        }
        exit();
    }

    // UPDATE
    if ($action === 'update') {
        $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        if (!$id) { echo json_encode(['success' => false, 'error' => 'Missing id']); exit(); }

        $title = $_POST['title'] ?? '';
        $content = $_POST['content'] ?? '';
        $category = $_POST['category'] ?? 'Policy';
        $link = $_POST['link'] ?? null;
        if (!$title || !$content) { echo json_encode(['success' => false, 'error' => 'Title and content are required']); exit(); }

        // get old attachment
        $stmt = $conn->prepare("SELECT attachment FROM announcements WHERE id = ?");
        $stmt->bind_param('i', $id);
        $stmt->execute();
        $res = $stmt->get_result();
        $row = $res->fetch_assoc();
        $oldAttachment = $row['attachment'] ?? null;

        $attachmentPath = $oldAttachment;
        $uploadResult = $handleUpload();
        if (is_array($uploadResult) && isset($uploadResult['error'])) {
            echo json_encode(['success' => false, 'error' => $uploadResult['error']]);
            exit();
        }
            if (is_array($uploadResult) && isset($uploadResult['path'])) {
            // new file uploaded; delete old
            if ($oldAttachment) {
                $fullOld = resolve_attachment_fullpath($oldAttachment);
                if ($fullOld && file_exists($fullOld)) @unlink($fullOld);
            }
            $attachmentPath = $uploadResult['path'];
        }

        $upd = $conn->prepare("UPDATE announcements SET title = ?, content = ?, category = ?, link = ?, attachment = ? WHERE id = ?");
        $upd->bind_param('sssssi', $title, $content, $category, $link, $attachmentPath, $id);
        if ($upd->execute()) {
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'error' => $conn->error]);
        }
        exit();
    }
}

// Other methods not allowed
http_response_code(405);
echo json_encode(['success' => false, 'error' => 'Method not allowed']);
exit();
