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

header('Content-Type: application/json');

// Check if user is admin
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

// Validate input
if (!isset($_POST['id']) || !isset($_POST['status'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
    exit;
}

$recordingId = (int)$_POST['id'];
$status = $_POST['status'];

// Validate status
if (!in_array($status, ['pending', 'approved', 'rejected'], true)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid status']);
    exit;
}

try {
    // Begin transaction
    $pdo->beginTransaction();
    
    // Update recording status
    $stmt = $pdo->prepare("UPDATE recordings SET status = ?, reviewed_at = NOW() WHERE id = ?");
    $stmt->execute([$status, $recordingId]);
    
    // If approved, update user points and mark task as complete
    if ($status === 'approved') {
        // Get the user ID and task ID for this recording
        $stmt = $pdo->prepare("SELECT user_id, task_id FROM recordings WHERE id = ?");
        $stmt->execute([$recordingId]);
        $recording = $stmt->fetch();
        
        if ($recording && $recording['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([$recording['user_id'], $recording['task_id']]);
            $taskCompleted = $stmt->rowCount() > 0;
            
            // Update user stats with points and today_completed count
            if ($taskCompleted) {
                // Task was newly completed, give full points and increment counter
                $stmt = $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()
                ");
                $stmt->execute([$recording['user_id']]);
            } else {
                // Task was already completed, just give 1 point for the recording
                $stmt = $pdo->prepare("
                    INSERT INTO user_stats (user_id, points, last_participation)
                    VALUES (?, 1, CURDATE())
                    ON DUPLICATE KEY UPDATE 
                        points = COALESCE(points, 0) + 1,
                        last_participation = CURDATE()
                ");
                $stmt->execute([$recording['user_id']]);
            }
            
            // Log the points awarded (only if point_history table exists)
            try {
                $stmt = $pdo->prepare("
                    INSERT INTO point_history (user_id, points, task_id, recording_id, type, created_at)
                    VALUES (?, ?, ?, ?, 'recording_approved', NOW())
                ");
                $points = $taskCompleted ? 10 : 1;
                $stmt->execute([$recording['user_id'], $points, $recording['task_id'], $recordingId]);
            } catch (Exception $e) {
                // point_history table might not exist, log but don't fail
                error_log("Could not log to point_history: " . $e->getMessage());
            }
        }
    }
    
    // Commit transaction
    $pdo->commit();
    
    echo json_encode(['success' => true]);
    
} catch (Exception $e) {
    // Rollback transaction on error
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    
    http_response_code(500);
    echo json_encode([
        'success' => false, 
        'message' => 'An error occurred while updating the recording status',
        'error' => $e->getMessage()
    ]);
}
