<?php
require_once '../../config/database.php';
require_once '../../includes/functions.php';

// Initialize database connection
if (!isset($conn)) {
    $conn = getConnection(); // Try function first
}
if (!isset($conn)) {
    // If still not set, create new connection
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    if ($conn->connect_error) {
        die(json_encode(['success' => false, 'message' => 'Database connection failed']));
    }
}

// Check admin authentication
if (!isset($_SESSION['admin_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$adminId = $_SESSION['admin_id'];

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

$submissionId = $input['submission_id'] ?? 0;
$rejectionReason = trim($input['rejection_reason'] ?? '');

// Validate input
if (!$submissionId || empty($rejectionReason)) {
    echo json_encode(['success' => false, 'message' => 'Invalid input']);
    exit();
}

try {
    // Update task_completions - mark as rejected
    $stmt = $conn->prepare("
        UPDATE task_completions 
        SET status = 'rejected',
            reviewed_at = NOW(),
            reviewer_id = ?,
            rejection_reason = ?
        WHERE id = ? 
        AND status = 'pending'
    ");
    $stmt->bind_param("isi", $adminId, $rejectionReason, $submissionId);
    $stmt->execute();

    if ($stmt->affected_rows == 0) {
        throw new Exception('Task already processed or not found');
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Task rejected successfully'
    ]);

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>