<?php
// --- DATABASE CONFIGURATION ---
// IMPORTANT: Replace with your actual database details from cPanel.
// I have used the details you provided for the Laravel project as an example.
$servername = "localhost";
$username = "cybsoul_loyality";      // <-- Your database username
$password = "Digital@1270";         // <-- Your database password
$dbname = "cybsoul_taskapp";         // <-- Your database name

// --- END OF CONFIGURATION ---

// --- Error Reporting (for debugging) ---
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Create database connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    // Send a JSON error response if connection fails
    header('Content-Type: application/json');
    die(json_encode(['status' => 'error', 'message' => 'Database connection failed: ' . $conn->connect_error]));
}

// Set the response header to indicate JSON content
header('Content-Type: application/json');

// Get the request body and decode it from JSON
$response = [];
$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? $_GET['action'] ?? ''; // Allow action via GET for simple tests

// --- API ROUTER ---
// This switch statement directs the request to the correct function based on the 'action' parameter.
switch ($action) {
    case 'getInitialData':
        $response = getInitialData($conn);
        break;

    case 'addDailyReport':
        $response = addDailyReport($conn, $input['data']);
        break;

    case 'getUserRatings':
        $response = getUserRatings($conn, $input['userId']);
        break;

    default:
        $response = ['status' => 'error', 'message' => 'Invalid action provided.'];
        break;
}

// Send the final JSON response back to the HTML page
echo json_encode($response);
$conn->close();


// --- FUNCTIONS ---

/**
 * Fetches the list of all users from the database.
 */
function getInitialData($conn) {
    $sql = "SELECT id, name FROM users ORDER BY name ASC";
    $result = $conn->query($sql);
    $users = [];
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $users[] = $row;
        }
    }
    return ['status' => 'success', 'users' => $users];
}

/**
 * Inserts a new daily report into the database.
 */
function addDailyReport($conn, $data) {
    $stmt = $conn->prepare("INSERT INTO daily_reports (user_id, report_date, regular_tasks_done, additional_tasks_done, tasks_overdue) VALUES (?, ?, ?, ?, ?)");
    $stmt->bind_param("isiii", $data['userId'], $data['date'], $data['regularTasks'], $data['additionalTasks'], $data['overdueTasks']);
    
    if ($stmt->execute()) {
        return ['status' => 'success', 'message' => 'Report added successfully.'];
    } else {
        return ['status' => 'error', 'message' => 'Failed to add report: ' . $stmt->error];
    }
    $stmt->close();
}

/**
 * Calculates and returns the ratings for a specific user.
 */
function getUserRatings($conn, $userId) {
    // Get settings
    $settings_sql = "SELECT setting_key, setting_value FROM settings";
    $settings_result = $conn->query($settings_sql);
    $settings = [];
    while($row = $settings_result->fetch_assoc()) {
        $settings[$row['setting_key']] = (float)$row['setting_value'];
    }

    // Prepare SQL statement to prevent SQL injection
    $reports_sql = $conn->prepare("SELECT report_date, regular_tasks_done, additional_tasks_done, tasks_overdue FROM daily_reports WHERE user_id = ?");
    $reports_sql->bind_param("i", $userId);
    $reports_sql->execute();
    $reports_result = $reports_sql->get_result();

    $dailyScore = 0;
    $weeklyScore = 0;
    $monthlyScore = 0;
    
    $today = new DateTime('now', new DateTimeZone('Asia/Kolkata'));
    $startOfWeek = (clone $today)->modify('monday this week');
    $startOfMonth = (clone $today)->modify('first day of this month');

    while($report = $reports_result->fetch_assoc()) {
        $score = ($report['regular_tasks_done'] * $settings['PointsPerRegularTask']) +
                 ($report['additional_tasks_done'] * $settings['PointsPerAdditionalTask']) +
                 ($report['tasks_overdue'] * $settings['PenaltyPerOverdueTask']);
        
        $reportDate = new DateTime($report['report_date']);

        if ($reportDate->format('Y-m-d') === $today->format('Y-m-d')) {
            $dailyScore += $score;
        }
        if ($reportDate >= $startOfWeek) {
            $weeklyScore += $score;
        }
        if ($reportDate >= $startOfMonth) {
            $monthlyScore += $score;
        }
    }
    
    $ratings = ['daily' => $dailyScore, 'weekly' => $weeklyScore, 'monthly' => $monthlyScore];
    $reports_sql->close();
    
    return ['status' => 'success', 'ratings' => $ratings];
}
?>
