<?php
// ============================================================
// ADDITIONAL API ENDPOINTS – append to hr_system/api/v1/index.php
// These new actions support the full role-based mobile app
// ============================================================

// ── LEAVE TYPES (for apply dialog) ───────────────────────────
if ($action === 'leave_types') {
    $types = $db->fetchAll("SELECT id, name, code FROM leave_types WHERE is_active=1 ORDER BY name");
    apiSuccess(['types' => $types]);
}

// ── APPLY LATE REGULARIZATION ─────────────────────────────────
if ($action === 'apply_late_regularization') {
    $date   = sanitize($input['date']   ?? date('Y-m-d'));
    $reason = sanitize($input['reason'] ?? '');
    if (!$reason) apiError('Reason is required');

    // Check attendance record exists for that date
    $att = $db->fetchOne(
        "SELECT id, late_minutes FROM attendance WHERE employee_id=? AND date=?",
        [$empId, $date]
    );
    if (!$att) apiError('No attendance record found for this date');

    // Check not already submitted
    $existing = $db->fetchOne(
        "SELECT id FROM late_regularizations WHERE employee_id=? AND date=? AND status != 'rejected'",
        [$empId, $date]
    );
    if ($existing) apiError('Late regularization already submitted for this date');

    $id = $db->insertRow('late_regularizations', [
        'employee_id'  => $empId,
        'date'         => $date,
        'late_minutes' => $att['late_minutes'] ?? 0,
        'reason'       => $reason,
        'status'       => 'pending',
    ]);
    apiSuccess(['request_id' => $id], 'Late regularization submitted');
}

// ── MY LATE REGULARIZATIONS ───────────────────────────────────
if ($action === 'my_late_regularizations') {
    $rows = $db->fetchAll(
        "SELECT lr.*, CONCAT(e.first_name,' ',e.last_name) AS approved_by_name
           FROM late_regularizations lr
      LEFT JOIN employees e ON e.id = (
                SELECT employee_id FROM users WHERE id = lr.approved_by LIMIT 1
              )
          WHERE lr.employee_id = ?
          ORDER BY lr.date DESC
          LIMIT 60",
        [$empId]
    );
    apiSuccess(['records' => $rows]);
}

// ── PENDING PERMISSIONS (for managers) ────────────────────────
if ($action === 'pending_permissions') {
    if (!in_array($authUser['role'], ['manager','hr','admin','superadmin'])) apiError('Access denied', 403);

    $where = in_array($authUser['role'], ['admin','superadmin'])
        ? "WHERE pr.status='pending'"
        : "WHERE pr.status='pending' AND e.reporting_manager_id=?";
    $params = in_array($authUser['role'], ['admin','superadmin']) ? [] : [$empId];

    $rows = $db->fetchAll(
        "SELECT pr.*, e.first_name, e.last_name, e.employee_id AS emp_code, e.id AS employee_id
           FROM permission_requests pr
           JOIN employees e ON e.id = pr.employee_id
           $where
           ORDER BY pr.permission_date DESC",
        $params
    );
    apiSuccess(['pending' => $rows, 'count' => count($rows)]);
}

// ── APPROVE PERMISSION ────────────────────────────────────────
if ($action === 'approve_permission') {
    if (!in_array($authUser['role'], ['manager','hr','admin','superadmin'])) apiError('Access denied', 403);
    $reqId  = (int)($input['request_id'] ?? 0);
    $status = sanitize($input['status'] ?? '');
    $remarks= sanitize($input['remarks'] ?? '');
    if (!$reqId || !in_array($status, ['approved','rejected'])) apiError('Invalid request');

    $req = $db->fetchOne("SELECT * FROM permission_requests WHERE id=?", [$reqId]);
    if (!$req) apiError('Request not found');
    if ($req['status'] !== 'pending') apiError('Already processed');

    $db->execute(
        "UPDATE permission_requests SET status=?,approved_by=?,approved_at=NOW(),remarks=? WHERE id=?",
        [$status, $empId, $remarks, $reqId]
    );
    apiSuccess(['status' => $status], "Permission $status");
}

// ── PENDING LATE MARKS (for managers) ─────────────────────────
if ($action === 'pending_late_marks') {
    if (!in_array($authUser['role'], ['manager','hr','admin','superadmin'])) apiError('Access denied', 403);

    $where = in_array($authUser['role'], ['admin','superadmin'])
        ? "WHERE lr.status='pending'"
        : "WHERE lr.status='pending' AND e.reporting_manager_id=?";
    $params = in_array($authUser['role'], ['admin','superadmin']) ? [] : [$empId];

    $rows = $db->fetchAll(
        "SELECT lr.*, e.first_name, e.last_name, e.employee_id AS emp_code, e.id AS employee_id
           FROM late_regularizations lr
           JOIN employees e ON e.id = lr.employee_id
           $where
           ORDER BY lr.date DESC",
        $params
    );
    apiSuccess(['pending' => $rows, 'count' => count($rows)]);
}

// ── APPROVE LATE MARK ─────────────────────────────────────────
if ($action === 'approve_late_mark') {
    if (!in_array($authUser['role'], ['manager','hr','admin','superadmin'])) apiError('Access denied', 403);
    $lateId = (int)($input['late_id'] ?? 0);
    $status = sanitize($input['status'] ?? '');
    $remarks= sanitize($input['remarks'] ?? '');
    if (!$lateId || !in_array($status, ['approved','rejected'])) apiError('Invalid request');

    $row = $db->fetchOne("SELECT * FROM late_regularizations WHERE id=?", [$lateId]);
    if (!$row) apiError('Record not found');
    if ($row['status'] !== 'pending') apiError('Already processed');

    $db->execute(
        "UPDATE late_regularizations SET status=?,approved_by=?,approved_at=NOW(),remarks=? WHERE id=?",
        [$status, $empId, $remarks, $lateId]
    );
    apiSuccess(['status' => $status], "Late mark $status");
}

// ── ALL PENDING APPROVALS (Management: admin + superadmin) ────
if ($action === 'all_pending_approvals') {
    if (!in_array($authUser['role'], ['admin','superadmin'])) apiError('Access denied', 403);

    $leaves = $db->fetchAll(
        "SELECT la.*, e.first_name, e.last_name, e.employee_id AS emp_code, lt.name AS lt_name
           FROM leave_applications la
           JOIN employees e ON e.id = la.employee_id
           JOIN leave_types lt ON lt.id = la.leave_type_id
          WHERE la.status = 'pending'
          ORDER BY la.created_at DESC"
    );
    $permissions = $db->fetchAll(
        "SELECT pr.*, e.first_name, e.last_name, e.employee_id AS emp_code
           FROM permission_requests pr
           JOIN employees e ON e.id = pr.employee_id
          WHERE pr.status = 'pending'
          ORDER BY pr.permission_date DESC"
    );
    $lateMarks = $db->fetchAll(
        "SELECT lr.*, e.first_name, e.last_name, e.employee_id AS emp_code
           FROM late_regularizations lr
           JOIN employees e ON e.id = lr.employee_id
          WHERE lr.status = 'pending'
          ORDER BY lr.date DESC"
    );
    apiSuccess([
        'leaves'      => $leaves,
        'permissions' => $permissions,
        'late_marks'  => $lateMarks,
        'total'       => count($leaves) + count($permissions) + count($lateMarks),
    ]);
}

// ── MANAGEMENT APPROVE (admin/superadmin approves any type) ───
if ($action === 'management_approve') {
    if (!in_array($authUser['role'], ['admin','superadmin'])) apiError('Access denied', 403);
    $type    = sanitize($input['type'] ?? '');
    $status  = sanitize($input['status'] ?? '');
    $remarks = sanitize($input['remarks'] ?? '');
    if (!in_array($status, ['approved','rejected'])) apiError('Invalid status');

    switch ($type) {
        case 'leave':
            $id = (int)($input['application_id'] ?? 0);
            if (!$id) apiError('Missing application_id');
            $app = $db->fetchOne("SELECT * FROM leave_applications WHERE id=?", [$id]);
            if (!$app || $app['status'] !== 'pending') apiError('Not found or already processed');
            $db->execute("UPDATE leave_applications SET status=?,approved_by=?,approved_at=NOW(),remarks=? WHERE id=?",
                [$status,$empId,$remarks,$id]);
            if ($status === 'approved') {
                $db->execute(
                    "INSERT INTO employee_leave_balance (employee_id,leave_type_id,year,allocated,used) VALUES (?,?,?,0,?) ON DUPLICATE KEY UPDATE used=used+?",
                    [$app['employee_id'],$app['leave_type_id'],date('Y'),$app['days'],$app['days']]
                );
            }
            break;
        case 'permission':
            $id = (int)($input['request_id'] ?? 0);
            if (!$id) apiError('Missing request_id');
            $db->execute("UPDATE permission_requests SET status=?,approved_by=?,approved_at=NOW(),remarks=? WHERE id=? AND status='pending'",
                [$status,$empId,$remarks,$id]);
            break;
        case 'late':
            $id = (int)($input['late_id'] ?? 0);
            if (!$id) apiError('Missing late_id');
            $db->execute("UPDATE late_regularizations SET status=?,approved_by=?,approved_at=NOW(),remarks=? WHERE id=? AND status='pending'",
                [$status,$empId,$remarks,$id]);
            break;
        default:
            apiError('Invalid type');
    }
    apiSuccess(['status' => $status], ucfirst($type) . " $status by management");
}

// ── TEAM REPORT (head/hr monthly summary) ────────────────────
if ($action === 'team_report') {
    if (!in_array($authUser['role'], ['manager','hr','admin','superadmin'])) apiError('Access denied', 403);
    $month = (int)($input['month'] ?? date('n'));
    $year  = (int)($input['year']  ?? date('Y'));

    $where  = in_array($authUser['role'], ['admin','superadmin','hr']) ? "" : "AND e.reporting_manager_id=$empId";
    $report = $db->fetchAll(
        "SELECT e.employee_id AS emp_code, e.first_name, e.last_name,
                COUNT(CASE WHEN a.status IN ('present','late') THEN 1 END) AS present,
                COUNT(CASE WHEN a.status = 'absent' THEN 1 END)            AS absent,
                COUNT(CASE WHEN a.status = 'late' THEN 1 END)              AS late,
                COUNT(CASE WHEN a.status = 'permission' THEN 1 END)        AS permission,
                COUNT(CASE WHEN a.status = 'leave' THEN 1 END)             AS leave_days
           FROM employees e
      LEFT JOIN attendance a ON a.employee_id = e.id
                             AND MONTH(a.date)=? AND YEAR(a.date)=?
          WHERE e.status = 'active' $where
          GROUP BY e.id
          ORDER BY e.first_name",
        [$month, $year]
    );
    apiSuccess(['report' => $report]);
}

// ── DASHBOARD (update to include pending_approvals_count) ─────
// NOTE: Add this inside the existing dashboard action:
// $pendingCount = 0;
// if (in_array($authUser['role'], ['manager','hr','admin','superadmin'])) {
//     $pendingCount = $db->fetchOne(
//         "SELECT COUNT(*) AS cnt FROM leave_applications la
//           JOIN employees e ON e.id=la.employee_id
//          WHERE la.status='pending'" .
//         (in_array($authUser['role'], ['admin','superadmin']) ? "" : " AND e.reporting_manager_id=$empId")
//     )['cnt'] ?? 0;
// }
// Then add 'pending_approvals_count' => (int)$pendingCount to the apiSuccess data array.
