<?php
require 'config/db.php';

// Get new projects not yet mapped
$projects = $pdo->query("
    SELECT p.id, p.sales_id, p.payment_received, DATE_FORMAT(p.created_at,'%Y-%m-01') as month
    FROM projects p
    LEFT JOIN project_achievement_map pam ON pam.project_id = p.id
    WHERE pam.project_id IS NULL AND p.payment_received > 0
")->fetchAll();

foreach($projects as $p){
    // Map project
    $pdo->prepare("
        INSERT INTO project_achievement_map (project_id, target_month, sales_employee_id, amount)
        VALUES (?, ?, ?, ?)
    ")->execute([$p['id'], $p['month'], $p['sales_id'], $p['payment_received']]);
// example: assume first manager id = 1
$manager_id = 1; // ya session se le sakte ho

$pdo->prepare("
    INSERT INTO team_targets (manager_id, target_month, target_value, achieved_amount)
    VALUES (?, ?, 0, ?)
    ON DUPLICATE KEY UPDATE achieved_amount = achieved_amount + VALUES(achieved_amount)
")->execute([$manager_id, $p['month'], $p['payment_received']]);

$pdo->prepare("
    INSERT INTO individual_targets (manager_id, sales_employee_id, target_month, target_value, achieved_amount, contribution)
    VALUES (?, ?, ?, 0, ?, ?)
    ON DUPLICATE KEY UPDATE 
        achieved_amount = achieved_amount + VALUES(achieved_amount),
        contribution = contribution + VALUES(contribution)
")->execute([$manager_id, $p['sales_id'], $p['month'], $p['payment_received'], $p['payment_received']]);
}

// Mark Completed
$pdo->query("UPDATE team_targets SET completed=1 WHERE achieved_amount >= target_value");
$pdo->query("UPDATE individual_targets SET completed=1 WHERE achieved_amount >= target_value");
