<?php
require 'config/db.php';
$emps = $pdo->query("SELECT id, full_name FROM sales_employees ORDER BY full_name")->fetchAll(PDO::FETCH_ASSOC);
$month = $_POST['month'] ?? date('n');
$year  = $_POST['year'] ?? date('Y');

$success = '';

if(isset($_POST['save_behavior'])) {

    $sales_id = $_POST['sales_id'] ?? null;
    $full_name = $_POST['full_name'] ?? '';
    $CRM_discipline = isset($_POST['CRM_discipline']) ? min(max($_POST['CRM_discipline'],0),3) : 0;
    $overtime = isset($_POST['overtime']) ? min(max($_POST['overtime'],0),4) : 0;
    $team_coordination = isset($_POST['team_coordination']) ? min(max($_POST['team_coordination'],0),3) : 0;

    if($sales_id) { 

        // Attendance points
        $attStmt = $pdo->prepare("
            SELECT COUNT(*) as present_days
            FROM sales_employee_attendance
            WHERE employee_id=? AND MONTH(att_date)=? AND YEAR(att_date)=? AND status='Present'
        ");
        $attStmt->execute([$sales_id,$month,$year]);
        $presentDays = (int)$attStmt->fetchColumn();
        $daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
        $attendancePercent = ($daysInMonth>0) ? ($presentDays/$daysInMonth)*100 : 0;

        if($attendancePercent >= 86) $attendance = 6;
        elseif($attendancePercent >= 76) $attendance = 5;
        elseif($attendancePercent >= 66) $attendance = 4;
        elseif($attendancePercent >= 51) $attendance = 3;
        elseif($attendancePercent >= 31) $attendance = 2;
        elseif($attendancePercent >= 1) $attendance = 1;
        else $attendance = 0;

        // Punctuality points
        $lateStmt = $pdo->prepare("
            SELECT COUNT(*) FROM sales_employee_late_log
            WHERE employee_id=? AND MONTH(log_date)=? AND YEAR(log_date)=? AND status='Late'
        ");
        $lateStmt->execute([$sales_id,$month,$year]);
        $lateCount = (int)$lateStmt->fetchColumn();

        if($lateCount == 0) $punctuality = 4;
        elseif($lateCount == 1) $punctuality = 3;
        elseif($lateCount == 2) $punctuality = 2;
        elseif($lateCount == 3) $punctuality = 1;
        else $punctuality = 0;

        // UPSERT
        $upsert = $pdo->prepare("
            INSERT INTO sales_behavior_kpi
            (sales_id, full_name, month, year, CRM_discipline, attendance, punctuality, overtime, team_coordination)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
                CRM_discipline = VALUES(CRM_discipline),
                attendance = VALUES(attendance),
                punctuality = VALUES(punctuality),
                overtime = VALUES(overtime),
                team_coordination = VALUES(team_coordination),
                updated_at = CURRENT_TIMESTAMP
        ");
        $upsert->execute([
            $sales_id, $full_name, $month, $year,
            $CRM_discipline, $attendance, $punctuality, $overtime, $team_coordination
        ]);

        $success = "Sales Behavior KPI updated successfully!";
    } else {
        $success = "Error: Please select an employee.";
    }
}
?>

<!-- ===== LAYOUT START ===== -->
<?php include 'assets/layout_top.php'; ?>
<br><br>
<div class="glass-panel">

<h3 class="mb-4 text-center"><i class="fa-solid fa-people-roof me-2"></i>Sales Behavior KPI</h3>

<?php if($success): ?>
<div class="alert alert-success text-center"><?= htmlspecialchars($success) ?></div>
<?php endif; ?>

<form method="post" class="mb-4">
<div class="row g-3">

<div class="col-md-4">
<label>Employee:</label>
<select name="sales_id" required class="form-select" onchange="this.form.full_name.value=this.options[this.selectedIndex].text">
<option value="">Select Employee</option>
<?php foreach($emps as $e){ ?>
<option value="<?=$e['id']?>"><?=$e['full_name']?></option>
<?php } ?>
</select>
<input type="hidden" name="full_name" value="">
</div>

<div class="col-md-2">
<label>Month:</label>
<select name="month" class="form-select">
<?php for($m=1;$m<=12;$m++){ ?>
<option value="<?=$m?>" <?=$m==$month?'selected':''?>><?=$m?></option>
<?php } ?>
</select>
</div>

<div class="col-md-2">
<label>Year:</label>
<input type="number" name="year" value="<?=$year?>" class="form-control">
</div>

<div class="col-md-2">
<label>CRM Discipline (0-3):</label>
<input type="number" name="CRM_discipline" min="0" max="3" value="0" class="form-control">
</div>

<div class="col-md-2">
<label>Overtime (0-4):</label>
<input type="number" name="overtime" min="0" max="4" value="0" class="form-control">
</div>

<div class="col-md-2">
<label>Team Coordination (0-3):</label>
<input type="number" name="team_coordination" min="0" max="3" value="0" class="form-control">
</div>

<div class="col-md-12 text-center mt-3">
<button type="submit" name="save_behavior" class="btn-main px-5">
<i class="fa-solid fa-floppy-disk me-1"></i> Save KPI
</button>
</div>

</div>
</form>

</div>

<?php include 'assets/layout_bottom.php'; ?>
