<?php
session_start();
require_once __DIR__ . '/includes/auth_check.php';
require_once __DIR__ . '/includes/db_connect.php';

$recording_id = intval($_POST['recording_id'] ?? 0);
$status = $_POST['status'] ?? '';
$note = trim($_POST['note'] ?? '');

if (!$recording_id || !in_array($status, ['approved','rejected'])) {
    header('Location: review_queue.php');
    exit;
}

// update recording
$stmt = $pdo->prepare("UPDATE recordings SET status=?, reviewer_id=?, reviewed_at=NOW() WHERE id=?");
$stmt->execute([$status, $_SESSION['admin_id'], $recording_id]);

// insert audit log
$stmt = $pdo->prepare("INSERT INTO audit_logs (admin_id, action, target_type, target_id, details) VALUES (?, 'review', 'recording', ?, ?)");
$stmt->execute([$_SESSION['admin_id'], $recording_id, $note]);

// if approved -> update user_stats and mark task as complete
if ($status === 'approved') {
    $rec = $pdo->prepare("SELECT user_id, task_id FROM recordings WHERE id=?");
    $rec->execute([$recording_id]);
    $r = $rec->fetch();
    if ($r && $r['task_id']) {
        $user_id = $r['user_id'];
        $task_id = $r['task_id'];
        
        // Mark the task as completed in user_tasks
        $stmt = $pdo->prepare("
            UPDATE user_tasks 
            SET status = 'completed',
                completed_at = NOW(),
                updated_at = NOW()
            WHERE user_id = ? 
            AND task_id = ? 
            AND status = 'assigned'
        ");
        $stmt->execute([$user_id, $task_id]);
        $taskCompleted = $stmt->rowCount() > 0;
        
        // Update user stats with proper points
        if ($taskCompleted) {
            // Task was newly completed, give 10 points and increment counter
            $pdo->prepare("
                INSERT INTO user_stats (user_id, points, today_completed, last_updated, last_participation) 
                VALUES (?, 10, 1, NOW(), CURDATE())
                ON DUPLICATE KEY UPDATE 
                    points = points + 10, 
                    today_completed = IF(DATE(last_updated) = CURDATE(), today_completed + 1, 1),
                    last_updated = NOW(),
                    last_participation = CURDATE()
            ")->execute([$user_id]);
        } else {
            // Task already completed, just give 1 point for the recording
            $pdo->prepare("
                INSERT INTO user_stats (user_id, points, last_participation) 
                VALUES (?, 1, CURDATE())
                ON DUPLICATE KEY UPDATE 
                    points = points + 1, 
                    last_participation = CURDATE()
            ")->execute([$user_id]);
        }
    }
}

header('Location: review_queue.php');
exit;
