<?php
// manage_users.php - HR Admin Panel
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ob_start();
session_start();

if (!isset($_SESSION['user_id']) || !in_array(strtolower($_SESSION['role'] ?? ''), ['superadmin','admin','md'])) {
    header('Location: index.php'); exit();
}

include 'config.php';
$fpdf_available = file_exists('fpdf/fpdf.php');
if ($fpdf_available) require_once 'fpdf/fpdf.php';

$upload_dir_rel   = 'uploads/';
$default_photo    = 'default-photo.jpg';
$username_session = $_SESSION['username'] ?? '';
$session_role     = strtolower($_SESSION['role'] ?? '');

// ── HELPERS ────────────────────────────────────────────────────────────────
function h($s) { return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8'); }

function user_photo_tag($photo, $upload_dir='uploads/', $default='default-photo.jpg', $alt='', $w=36, $h=36) {
    $root = rtrim($_SERVER['DOCUMENT_ROOT'],'/');
    $dir  = $root.'/'.trim($upload_dir,'/').'/';
    $src  = ($photo && $photo !== '') ? $photo : $default;
    if (!file_exists($dir.$src)) {
        $init = strtoupper(substr(strip_tags($alt),0,1)?:'U');
        return '<div class="av" title="'.h($alt).'">'.$init.'</div>';
    }
    $url = '/'.trim($upload_dir,'/').'/' . rawurlencode($src);
    return '<img src="'.h($url).'?v='.time().'" width="'.$w.'" height="'.$h.'" alt="'.h($alt).'" class="emp-thumb" loading="lazy">';
}

function fetchUser($conn, $id) {
    $s = $conn->prepare('SELECT * FROM users WHERE id=?');
    if (!$s) return null;
    $s->bind_param('s',$id); $s->execute();
    $r = $s->get_result()->fetch_assoc(); $s->close(); return $r;
}

function fetchAllUsers($conn) {
    $r = $conn->query('SELECT * FROM users WHERE status NOT IN ("resigned","deleted") AND role!="superadmin" ORDER BY first_name,last_name');
    return $r ? $r->fetch_all(MYSQLI_ASSOC) : [];
}

function fetchDeletedUsers($conn) {
    $r = $conn->query('SELECT * FROM users WHERE status IN ("resigned","deleted") AND role!="superadmin" ORDER BY resignation_date DESC');
    return $r ? $r->fetch_all(MYSQLI_ASSOC) : [];
}

// Fetch all active users as a flat id=>name map for reporting manager dropdown
function fetchUserMap($conn) {
    $r = $conn->query('SELECT id, first_name, last_name, username FROM users WHERE status NOT IN ("resigned","deleted") AND role!="superadmin" ORDER BY first_name, last_name');
    $map = [];
    if ($r) {
        while ($row = $r->fetch_assoc()) {
            $name = trim(($row['first_name']??'').' '.($row['last_name']??''));
            $map[$row['id']] = $name ?: ($row['username'] ?? $row['id']);
        }
    }
    return $map;
}

// Resolve reporting_manager_id to a name; fallback to reporting_manager text field
function resolveManagerName($conn, $user, $userMap) {
    $mid = trim($user['reporting_manager_id'] ?? '');
    if ($mid !== '' && isset($userMap[$mid])) {
        return $userMap[$mid];
    }
    // fallback: try to find by name in map
    $mname = trim($user['reporting_manager'] ?? '');
    if ($mname !== '') return $mname;
    return '';
}

function ensureOfferColumns($conn) {
    $cols = ['offer_released'=>'TINYINT(1) DEFAULT 0','offer_released_at'=>'DATETIME DEFAULT NULL',
             'offer_accepted'=>"VARCHAR(20) DEFAULT 'Pending'",'offer_accepted_at'=>'DATETIME DEFAULT NULL','offer_seen'=>'TINYINT(1) DEFAULT 0'];
    foreach ($cols as $c => $def) {
        $r = $conn->query("SHOW COLUMNS FROM `users` LIKE '{$c}'");
        if ($r && $r->num_rows == 0) @$conn->query("ALTER TABLE `users` ADD COLUMN `{$c}` {$def}");
    }
}

function createNotification($conn, $uid, $msg) {
    $r = $conn->query("SHOW TABLES LIKE 'notifications'");
    if (!$r || $r->num_rows == 0) return;
    $col = null;
    if ($conn->query("SHOW COLUMNS FROM `notifications` LIKE 'user_id'")->num_rows) $col='user_id';
    elseif ($conn->query("SHOW COLUMNS FROM `notifications` LIKE 'employee_id'")->num_rows) $col='employee_id';
    if ($col) { $s=$conn->prepare("INSERT INTO notifications(`{$col}`,message,created_at)VALUES(?,?,NOW())"); if($s){$s->bind_param('ss',$uid,$msg);$s->execute();$s->close();} }
}

function setFlash($type, $html, $to='manage_users.php') {
    $_SESSION['flash_message'] = ['type'=>$type,'html'=>$html];
    header('Location:'.$to); exit;
}

function empName($u) {
    $n = trim(($u['first_name']??'').' '.($u['last_name']??''));
    return $n ?: ($u['username'] ?? 'User');
}

// ── APPOINTMENT PDF ────────────────────────────────────────────────────────
function generateAppointmentPDF($conn, $uid, $udir, &$err=null) {
    global $fpdf_available;
    if (!$fpdf_available) { $err='FPDF not found.'; return false; }
    $u = fetchUser($conn, $uid);
    if (!$u) { $err='User not found.'; return false; }
    $dir = rtrim($_SERVER['DOCUMENT_ROOT'],'/').'/'.trim($udir,'/').'/user_'.$uid.'/';
    if (!is_dir($dir) && !@mkdir($dir,0775,true)) { $err='Cannot create upload folder.'; return false; }
    $file = $dir.'appointment_letter.pdf';
    $name = empName($u); $company=$u['Company']??'Company'; $doj=$u['date_of_joining']??date('Y-m-d');
    try {
        $pdf = new FPDF('P','mm','A4'); $pdf->AddPage(); $pdf->SetMargins(25,20,25);
        $pdf->SetFont('Arial','B',16); $pdf->Cell(0,10,$company,0,1,'C');
        $pdf->SetFont('Arial','',10); $pdf->Cell(0,6,'HR Department',0,1,'C'); $pdf->Ln(4);
        $pdf->Line(25,$pdf->GetY(),185,$pdf->GetY()); $pdf->Ln(6);
        $pdf->SetFont('Arial','BU',13); $pdf->Cell(0,8,'APPOINTMENT LETTER',0,1,'C'); $pdf->Ln(6);
        $pdf->SetFont('Arial','',11);
        foreach (['Ref No:'=>'HR/'.strtoupper(substr($uid,0,6)).'/'.date('Y'),'Date:'=>date('d-m-Y')] as $l=>$v)
            { $pdf->Cell(50,7,$l,0,0); $pdf->Cell(0,7,$v,0,1); }
        $pdf->Ln(6); $pdf->Cell(0,7,'To,',0,1);
        $pdf->SetFont('Arial','B',11); $pdf->Cell(0,7,$name,0,1);
        $pdf->SetFont('Arial','',11);
        if (!empty($u['address'])) $pdf->MultiCell(0,6,$u['address'],0,'L');
        $pdf->Ln(6);
        $pdf->MultiCell(0,7,'Dear '.($u['first_name']??$name).',',0,'L'); $pdf->Ln(4);
        $pdf->MultiCell(0,7,'We are pleased to appoint you in our organization on the following terms and conditions:',0,'L'); $pdf->Ln(4);
        $rows=[['Designation',$u['designation']??''],['Department',$u['division']??''],
               ['Date of Joining',$doj],['Location',$u['location']??''],
               ['Appointment Type',ucfirst($u['appointment_type']??'regular')],
               ['Basic Salary','Rs. '.number_format((float)($u['basic_salary']??0),2).' p.m.'],
               ['Level',$u['level']??'L1']];
        $pdf->SetFillColor(240,240,240);
        foreach ($rows as $i=>$r) {
            $f=($i%2===0);
            $pdf->SetFont('Arial','B',10); $pdf->Cell(70,8,$r[0],1,0,'L',$f);
            $pdf->SetFont('Arial','',10);  $pdf->Cell(0,8,$r[1],1,1,'L',$f);
        }
        $pdf->Ln(8); $pdf->SetFont('Arial','B',11); $pdf->Cell(0,7,'Terms & Conditions:',0,1);
        $pdf->SetFont('Arial','',10);
        $terms=['Probation period of 6 months from date of joining.',
                'Services liable to transfer to any department or location.',
                'Maintain strict confidentiality of company data.',
                'Submit all required documents in original.',
                'Subject to company HR policy terms.'];
        foreach ($terms as $i=>$t) { $pdf->MultiCell(0,6,($i+1).'. '.$t,0,'L'); $pdf->Ln(1); }
        $pdf->Ln(8); $pdf->MultiCell(0,7,'We wish you a successful tenure with us.',0,'L'); $pdf->Ln(12);
        $pdf->SetFont('Arial','B',10);
        $pdf->Cell(90,6,'Authorised Signatory',0,0); $pdf->Cell(0,6,'Employee Signature & Date',0,1);
        $pdf->SetFont('Arial','',9); $pdf->Cell(90,6,'('.$company.')',0,0); $pdf->Ln(4);
        $pdf->SetFont('Arial','I',8); $pdf->Cell(0,6,'Generated: '.date('d-m-Y H:i:s'),0,1,'R');
        $pdf->Output('F',$file);
    } catch (Exception $e) { $err='PDF error: '.$e->getMessage(); return false; }
    return file_exists($file);
}

// ── DOWNLOAD ALL (CSV) ─────────────────────────────────────────────────────
function downloadAllEmployees($conn) {
    $sql = "SELECT u.*, CONCAT(IFNULL(m.first_name,''),' ',IFNULL(m.last_name,'')) AS reporting_manager_name
            FROM users u
            LEFT JOIN users m ON m.id = u.reporting_manager_id
            WHERE u.role != 'superadmin'
            ORDER BY u.first_name, u.last_name";
    $res = $conn->query($sql);
    if (!$res) { $_SESSION['flash_message']=['type'=>'danger','html'=>'Query failed: '.h($conn->error)]; header('Location:manage_users.php'); exit; }
    $rows = $res->fetch_all(MYSQLI_ASSOC);
    while(ob_get_level()) ob_end_clean();
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="employees_'.date('Ymd_His').'.csv"');
    header('Pragma: no-cache'); header('Expires: 0');
    $out = fopen('php://output','w');
    fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF));
    if ($rows) csvWriteRow($out, array_keys($rows[0]));
    foreach ($rows as $row) csvWriteRow($out, $row);
    fclose($out); exit;
}


// ── BULK EMPLOYEE UPLOAD / EXCEL TEMPLATE ──────────────────────────────────
function tableExists($conn, $table) {
    $table = $conn->real_escape_string($table);
    $r = $conn->query("SHOW TABLES LIKE '{$table}'");
    return $r && $r->num_rows > 0;
}

function tableColumns($conn, $table) {
    $cols = [];
    $r = $conn->query("SHOW COLUMNS FROM `{$table}`");
    if ($r) while ($row = $r->fetch_assoc()) $cols[$row['Field']] = $row;
    return $cols;
}

function pickCol($cols, $names) {
    foreach ($names as $n) if (isset($cols[$n])) return $n;
    return null;
}

function cleanCell($v) {
    $v = trim((string)$v);
    $v = preg_replace('/^\xEF\xBB\xBF/', '', $v);
    return $v;
}

// PHP 8.4 safe CSV reader: explicitly pass escape parameter.
function csvReadRow($fh) {
    return fgetcsv($fh, 0, ',', '"', '\\');
}

// PHP 8.4 safe CSV writer: explicitly pass escape parameter.
function csvWriteRow($fh, $row) {
    return fputcsv($fh, $row, ',', '"', '\\');
}

function nullableUserId($conn, $v) {
    $v = cleanCell($v);
    if ($v === '' || strtolower($v) === 'null' || strtolower($v) === 'na') return null;

    $s = $conn->prepare("SELECT id FROM users WHERE id=? LIMIT 1");
    if (!$s) return null;
    $s->bind_param('s', $v);
    $s->execute();
    $row = $s->get_result()->fetch_assoc();
    $s->close();

    return $row ? $row['id'] : null;
}

function parseExcelDate($v) {
    $v = cleanCell($v);
    if ($v === '' || strtolower($v) === 'null') return null;
    if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $v)) return $v;
    if (preg_match('/^(\d{1,2})[-\/](\d{1,2})[-\/](\d{4})$/', $v, $m)) return sprintf('%04d-%02d-%02d', $m[3], $m[2], $m[1]);
    if (is_numeric($v) && (float)$v > 25000) return date('Y-m-d', ((float)$v - 25569) * 86400);
    $t = strtotime($v);
    return $t ? date('Y-m-d', $t) : null;
}

function csvValue($row, $map, $aliases, $default='') {
    foreach ($aliases as $a) {
        $k = strtolower(trim($a));
        if (isset($map[$k]) && isset($row[$map[$k]])) return cleanCell($row[$map[$k]]);
    }
    return $default;
}

function nextEmployeeId($conn) {
    $r = $conn->query("SELECT MAX(CAST(id AS UNSIGNED)) AS mx FROM users WHERE id REGEXP '^[0-9]+$'");
    $mx = ($r && ($row=$r->fetch_assoc())) ? (int)$row['mx'] : 0;
    return (string)($mx + 1);
}

function findDepartmentByName($conn, $name) {
    $name = cleanCell($name);
    if ($name === '') return [null, ''];
    foreach (['divisions','departments','division','department'] as $tbl) {
        if (!tableExists($conn, $tbl)) continue;
        $cols = tableColumns($conn, $tbl);
        $idCol = pickCol($cols, ['id','division_id','department_id']);
        $nameCol = pickCol($cols, ['division_name','department_name','name','title']);
        if (!$idCol || !$nameCol) continue;
        $s = $conn->prepare("SELECT `$idCol` AS id, `$nameCol` AS name FROM `$tbl` WHERE LOWER(`$nameCol`) = LOWER(?) LIMIT 1");
        if (!$s) continue;
        $s->bind_param('s', $name); $s->execute();
        $row = $s->get_result()->fetch_assoc(); $s->close();
        if ($row) return [$row['id'], $row['name']];
    }
    return [null, $name];
}

function findDesignationByName($conn, $name, $divisionId=null) {
    $name = cleanCell($name);
    if ($name === '') return [null, ''];
    if (!tableExists($conn, 'designations')) return [null, $name];
    $sql = "SELECT id, designation_name FROM designations WHERE LOWER(designation_name)=LOWER(?)";
    $types = 's'; $vals = [$name];
    if ($divisionId !== null && $divisionId !== '') { $sql .= " AND division_id=?"; $types .= 's'; $vals[] = $divisionId; }
    $sql .= " ORDER BY status DESC, id ASC LIMIT 1";
    $s = $conn->prepare($sql);
    if (!$s) return [null, $name];
    $s->bind_param($types, ...$vals); $s->execute();
    $row = $s->get_result()->fetch_assoc(); $s->close();
    return $row ? [$row['id'], $row['designation_name']] : [null, $name];
}

function findUserIdByNameOrId($conn, $v) {
    $v = cleanCell($v);
    if ($v === '') return [null, ''];
    $s = $conn->prepare("SELECT id, first_name, last_name, username FROM users WHERE id=? OR username=? OR LOWER(CONCAT(IFNULL(first_name,''),' ',IFNULL(last_name,'')))=LOWER(?) LIMIT 1");
    if (!$s) return [null, $v];
    $s->bind_param('sss', $v, $v, $v); $s->execute();
    $row = $s->get_result()->fetch_assoc(); $s->close();
    if (!$row) return [null, $v];
    $name = trim(($row['first_name']??'').' '.($row['last_name']??''));
    return [$row['id'], $name ?: ($row['username'] ?? $row['id'])];
}

function downloadEmployeeTemplate($conn) {
    while(ob_get_level()) ob_end_clean();
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="employee_bulk_upload_template_'.date('Ymd_His').'.csv"');
    header('Pragma: no-cache'); header('Expires: 0');
    $out = fopen('php://output','w');
    fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF));
    $headers = ['id','username','password','email','role','first_name','last_name','mobileno','designation','department','division','reporting_manager','basic_salary','gender','dob','date_of_joining','father_name','qualification','bank_name','account_number','ifsc_code','level','appointment_type','location','Company','status','emergency_contact_no','marital_status','anniversary_date'];
    csvWriteRow($out, $headers);
    csvWriteRow($out, ['','EMP001','123456','emp001@example.com','employee','First','Last','9876543210','Telecalling Executive','Sales','Sales','Manager Name or ID','15000','Male','1995-01-01','2026-06-10','Father Name','Degree','Bank Name','1234567890','IFSC0001234','L1','regular','Salem','SPICA HO','active','9876543210','Single','1970-01-01']);
    csvWriteRow($out, []);
    csvWriteRow($out, ['Notes']);
    csvWriteRow($out, ['Use CSV format only. Do not rename headers. Existing id/username will be updated; new rows will be inserted.']);
    csvWriteRow($out, []);
    csvWriteRow($out, ['Available designations from designations table']);
    if (tableExists($conn,'designations')) {
        $r = $conn->query("SELECT id, division_id, designation_name, status FROM designations ORDER BY designation_name");
        if ($r) while($d=$r->fetch_assoc()) csvWriteRow($out, [$d['id'],$d['division_id'],$d['designation_name'],$d['status']]);
    }
    fclose($out); exit;
}

function handleEmployeeBulkUpload($conn) {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_FILES['employee_excel']['tmp_name'])) setFlash('danger','Please choose a CSV file to upload.');
    $ext = strtolower(pathinfo($_FILES['employee_excel']['name'] ?? '', PATHINFO_EXTENSION));
    if (!in_array($ext, ['csv','txt'])) setFlash('danger','Upload CSV only. Download the Excel template, fill it, then save as CSV.');
    if ($_FILES['employee_excel']['size'] > 8*1024*1024) setFlash('danger','File is too large. Maximum allowed size is 8 MB.');

    $fh = fopen($_FILES['employee_excel']['tmp_name'], 'r');
    if (!$fh) setFlash('danger','Cannot read uploaded file.');
    $headers = csvReadRow($fh);
    if (!$headers) setFlash('danger','CSV header row missing.');
    $map = [];
    foreach ($headers as $i=>$h) $map[strtolower(trim(preg_replace('/^\xEF\xBB\xBF/', '', $h)))] = $i;

    $userCols = tableColumns($conn, 'users');
    $inserted=0; $updated=0; $skipped=0; $errors=[]; $line=1;

    while (($row = csvReadRow($fh)) !== false) {
        $line++;
        if (!$row || count(array_filter($row, fn($x)=>trim((string)$x)!=='')) === 0) continue;
        $firstCell = strtolower(cleanCell($row[0] ?? ''));
        if ($firstCell === 'notes' || str_starts_with($firstCell, 'available designations')) break;

        $id       = csvValue($row,$map,['id','employee_id','emp id']);
        $username = csvValue($row,$map,['username','user name']);
        $email    = csvValue($row,$map,['email','email id']);
        if ($id === '' && $username === '' && $email === '') { $skipped++; continue; }
        if ($id === '') $id = nextEmployeeId($conn);
        if ($username === '') $username = 'EMP'.$id;

        $deptInput = csvValue($row,$map,['department','division','department_name','division_name']);
        [$divisionId,$divisionName] = findDepartmentByName($conn, $deptInput);
        $desigInput = csvValue($row,$map,['designation','designation_name']);
        [$designationId,$designationName] = findDesignationByName($conn, $desigInput, $divisionId);
        [$managerId,$managerName] = findUserIdByNameOrId($conn, csvValue($row,$map,['reporting_manager','reporting_manager_id','manager']));

        $data = [
            'id'=>$id,
            'username'=>$username,
            'password'=>csvValue($row,$map,['password'], '123456'),
            'email'=>$email,
            'role'=>csvValue($row,$map,['role'], 'employee') ?: 'employee',
            'reporting_manager'=>$managerName,
            'is_superadmin'=>'0',
            'status'=>csvValue($row,$map,['status'], 'active') ?: 'active',
            'basic_salary'=>csvValue($row,$map,['basic_salary','salary'], '0.00') ?: '0.00',
            'responsibilities'=>csvValue($row,$map,['responsibilities'], 'Pending') ?: 'Pending',
            'mobileno'=>csvValue($row,$map,['mobileno','mobile','mobile_number']),
            'designation'=>$designationName ?: $desigInput,
            'emergency_contact_no'=>csvValue($row,$map,['emergency_contact_no','emergency_contact_phone'], '0') ?: '0',
            'emergency_contact_name'=>csvValue($row,$map,['emergency_contact_name','emergency_contact_person']),
            'emergency_contact_phone'=>csvValue($row,$map,['emergency_contact_phone']),
            'emergency_contact_person'=>csvValue($row,$map,['emergency_contact_person']),
            'emergency_contact_relationship'=>csvValue($row,$map,['emergency_contact_relationship']),
            'division'=>$divisionName ?: $deptInput,
            'division_id'=>$divisionId,
            'designation_id'=>$designationId,
            'reporting_manager_id'=>$managerId,
            'md_id'=>nullableUserId($conn, csvValue($row,$map,['md_id','md','managing_director_id'])),
            'marital_status'=>csvValue($row,$map,['marital_status'], 'Single') ?: 'Single',
            'anniversary_date'=>parseExcelDate(csvValue($row,$map,['anniversary_date'])) ?: '1970-01-01',
            'gender'=>csvValue($row,$map,['gender'], 'Male') ?: 'Male',
            'dob'=>parseExcelDate(csvValue($row,$map,['dob','date_of_birth'])),
            'date_of_joining'=>parseExcelDate(csvValue($row,$map,['date_of_joining','doj'])),
            'father_name'=>csvValue($row,$map,['father_name'], 'NA') ?: 'NA',
            'spouse_name'=>csvValue($row,$map,['spouse_name']),
            'qualification'=>csvValue($row,$map,['qualification'], 'NA') ?: 'NA',
            'previous_experience'=>csvValue($row,$map,['previous_experience']),
            'company_name'=>csvValue($row,$map,['company_name']),
            'total_experience_years'=>csvValue($row,$map,['total_experience_years'], '0') ?: '0',
            'bank_name'=>csvValue($row,$map,['bank_name'], 'NA') ?: 'NA',
            'account_number'=>csvValue($row,$map,['account_number'], 'NA') ?: 'NA',
            'ifsc_code'=>csvValue($row,$map,['ifsc_code'], 'NA') ?: 'NA',
            'first_name'=>csvValue($row,$map,['first_name','firstname'], $username) ?: $username,
            'last_name'=>csvValue($row,$map,['last_name','lastname']),
            'level'=>csvValue($row,$map,['level'], 'L1') ?: 'L1',
            'performance'=>csvValue($row,$map,['performance'], '0') ?: '0',
            'position'=>csvValue($row,$map,['position']),
            'appointment_type'=>csvValue($row,$map,['appointment_type'], 'regular') ?: 'regular',
            'location'=>csvValue($row,$map,['location']),
            'Company'=>csvValue($row,$map,['Company','company'], 'SPICA HO') ?: 'SPICA HO',
            'responsibilities_accepted'=>'Pending',
            'details_accepted'=>'Pending',
            'offer_accepted'=>'Pending',
            'offer_released'=>'0',
            'offer_seen'=>'0',
            'created_at'=>date('Y-m-d H:i:s')
        ];

        $check = $conn->prepare("SELECT id FROM users WHERE id=? OR username=? LIMIT 1");
        if (!$check) { $errors[] = "Line {$line}: DB check failed - ".$conn->error; continue; }
        $check->bind_param('ss',$id,$username); $check->execute();
        $exists = $check->get_result()->fetch_assoc(); $check->close();

        $final = [];
        foreach ($data as $k=>$v) if (isset($userCols[$k])) $final[$k] = $v;
        foreach ($userCols as $c=>$meta) {
            if (array_key_exists($c,$final)) continue;
            if (($meta['Null'] ?? '') === 'NO' && ($meta['Default'] ?? null) === null && stripos($meta['Extra'] ?? '', 'auto_increment') === false) {
                if (stripos($meta['Type'],'int') !== false || stripos($meta['Type'],'decimal') !== false) $final[$c] = 0;
                elseif (stripos($meta['Type'],'date') !== false) $final[$c] = (stripos($meta['Type'],'datetime') !== false ? date('Y-m-d H:i:s') : '1970-01-01');
                else $final[$c] = 'NA';
            }
        }

        if ($exists) {
            unset($final['id'], $final['created_at']);
            $sets=[]; $vals=[]; $types='';
            foreach ($final as $k=>$v) { $sets[]="`$k`=?"; $vals[]=$v; $types.='s'; }
            if (isset($userCols['updated_at'])) { $sets[]="`updated_at`=NOW()"; }
            $vals[] = $exists['id']; $types .= 's';
            $sql = "UPDATE users SET ".implode(',', $sets)." WHERE id=?";
            $s = $conn->prepare($sql);
            if (!$s) { $errors[]="Line {$line}: update prepare failed - ".$conn->error; continue; }
            $s->bind_param($types, ...$vals);
            if ($s->execute()) $updated++; else $errors[]="Line {$line}: update failed - ".$s->error;
            $s->close();
        } else {
            $cols = array_keys($final);
            $place = implode(',', array_fill(0,count($cols),'?'));
            $sql = "INSERT INTO users (`".implode('`,`',$cols)."`) VALUES ($place)";
            $vals = array_values($final); $types = str_repeat('s', count($vals));
            $s = $conn->prepare($sql);
            if (!$s) { $errors[]="Line {$line}: insert prepare failed - ".$conn->error; continue; }
            $s->bind_param($types, ...$vals);
            if ($s->execute()) $inserted++; else $errors[]="Line {$line}: insert failed - ".$s->error;
            $s->close();
        }
    }
    fclose($fh);
    $html = "Bulk upload completed. Inserted: <b>{$inserted}</b>, Updated: <b>{$updated}</b>, Skipped: <b>{$skipped}</b>.";
    if ($errors) $html .= '<br><b>Errors:</b><br>'.h(implode("\n", array_slice($errors,0,10)));
    setFlash($errors ? 'danger' : 'success', $html);
}

function handleBulkEmployeeAction($conn, $udir) {
    $ids = $_POST['selected_users'] ?? [];
    $action = $_POST['bulk_action'] ?? '';
    if (!$ids || !is_array($ids)) setFlash('danger','Select at least one employee.');
    $done=0; $failed=0;
    foreach ($ids as $uid) {
        $uid = trim((string)$uid);
        if ($uid === '') continue;
        if ($action === 'release_letters') {
            $err=null;
            if (generateAppointmentPDF($conn,$uid,$udir,$err)) {
                $s=$conn->prepare("UPDATE users SET offer_released=1,offer_released_at=NOW(),offer_seen=0,offer_accepted='Pending' WHERE id=?");
                if($s){$s->bind_param('s',$uid);$s->execute();$s->close();$done++;} else $failed++;
            } else $failed++;
        } elseif ($action === 'mark_seen') {
            $s=$conn->prepare("UPDATE users SET offer_seen=1 WHERE id=?");
            if($s){$s->bind_param('s',$uid);$s->execute();$s->close();$done++;} else $failed++;
        } elseif ($action === 'remove_letters') {
            $file=rtrim($_SERVER['DOCUMENT_ROOT'],'/').'/'.trim($udir,'/').'/user_'.$uid.'/appointment_letter.pdf';
            if (file_exists($file)) @unlink($file);
            $s=$conn->prepare("UPDATE users SET offer_released=0,offer_released_at=NULL,offer_seen=0,offer_accepted='Pending' WHERE id=?");
            if($s){$s->bind_param('s',$uid);$s->execute();$s->close();$done++;} else $failed++;
        } elseif ($action === 'resign') {
            $s=$conn->prepare("UPDATE users SET status='resigned',resignation_date=NOW() WHERE id=?");
            if($s){$s->bind_param('s',$uid);$s->execute();$s->close();$done++;} else $failed++;
        }
    }
    setFlash($failed ? 'danger' : 'success', "Bulk action completed. Success: <b>{$done}</b>, Failed: <b>{$failed}</b>.");
}

// ── UPDATE REPORTING MANAGER ───────────────────────────────────────────────
function updateReportingManager($conn) {
    $uid  = trim($_POST['emp_id'] ?? '');
    $mid  = trim($_POST['manager_id'] ?? '');
    if ($uid === '') { setFlash('danger','Employee ID missing.'); }
    if ($mid === $uid) { setFlash('danger','An employee cannot be their own manager.'); }

    // Fetch manager name for the text column
    $mname = '';
    if ($mid !== '') {
        $mu = fetchUser($conn, $mid);
        if ($mu) $mname = empName($mu);
    }

    $s = $conn->prepare("UPDATE users SET reporting_manager_id=?, reporting_manager=? WHERE id=?");
    if (!$s) { setFlash('danger','DB error: '.h($conn->error)); }
    $s->bind_param('sss', $mid, $mname, $uid);
    $ok = $s->execute(); $e = $s->error; $s->close();
    if ($ok) {
        setFlash('success','Reporting manager updated successfully for employee '.h($uid).'.');
    } else {
        setFlash('danger','Update failed: '.h($e));
    }
}

// ── APPOINTMENT ACTIONS ────────────────────────────────────────────────────
function releaseAppointment($conn,$uid,$udir) {
    ensureOfferColumns($conn);
    $err=null;
    if (!generateAppointmentPDF($conn,$uid,$udir,$err)) setFlash('danger',$err?:h($err));
    $file=rtrim($_SERVER['DOCUMENT_ROOT'],'/').'/'.trim($udir,'/').'/user_'.$uid.'/appointment_letter.pdf';
    if (!file_exists($file)) setFlash('danger','Failed to save PDF.');
    $s=$conn->prepare("UPDATE users SET offer_released=1,offer_released_at=NOW(),offer_seen=0,offer_accepted='Pending' WHERE id=?");
    if ($s) { $s->bind_param('s',$uid); $s->execute(); $s->close(); }
    createNotification($conn,$uid,'Your appointment letter is available. Please log in to view it.');
    $url='/'.ltrim(trim($udir,'/').'/user_'.$uid.'/appointment_letter.pdf','/');
    setFlash('success','Letter released. <a href="'.h($url).'" target="_blank" style="color:#065f46;font-weight:700;text-decoration:underline">View PDF</a>');
}

function recreateAppointment($conn,$uid,$udir) {
    ensureOfferColumns($conn);
    $err=null;
    if (!generateAppointmentPDF($conn,$uid,$udir,$err)) setFlash('danger',$err?:h($err));
    $s=$conn->prepare("UPDATE users SET offer_released=1,offer_released_at=NOW(),offer_seen=0 WHERE id=?");
    if ($s) { $s->bind_param('s',$uid); $s->execute(); $s->close(); }
    $url='/'.ltrim(trim($udir,'/').'/user_'.$uid.'/appointment_letter.pdf','/');
    setFlash('success','Letter updated. <a href="'.h($url).'" target="_blank" style="color:#065f46;font-weight:700;text-decoration:underline">View PDF</a>');
}

function removeAppointment($conn,$uid,$udir) {
    $file=rtrim($_SERVER['DOCUMENT_ROOT'],'/').'/'.trim($udir,'/').'/user_'.$uid.'/appointment_letter.pdf';
    if (file_exists($file)) @unlink($file);
    $s=$conn->prepare("UPDATE users SET offer_released=0,offer_released_at=NULL,offer_seen=0,offer_accepted='Pending' WHERE id=?");
    if ($s) { $s->bind_param('s',$uid); $s->execute(); $s->close(); }
    setFlash('success','Letter removed for user '.h($uid).'.');
}

function markOfferSeen($conn,$uid) {
    ensureOfferColumns($conn);
    $s=$conn->prepare("UPDATE users SET offer_seen=1 WHERE id=?");
    if ($s) { $s->bind_param('s',$uid); $s->execute(); $s->close(); }
    setFlash('success','Marked as seen.');
}

function resignUser($conn,$uid) {
    $s=$conn->prepare("UPDATE users SET status='resigned',resignation_date=NOW() WHERE id=?");
    if ($s) { $s->bind_param('s',$uid); $s->execute(); $s->close(); }
    setFlash('success','Employee resigned.');
}

function restoreUser($conn,$uid) {
    $s=$conn->prepare("UPDATE users SET status='active',resignation_date=NULL,rejoin_date=NOW() WHERE id=?");
    if ($s) { $s->bind_param('s',$uid); $s->execute(); $s->close(); }
    setFlash('success','Employee restored to active.');
}

function handleDocumentsUpload($conn,$uid,$udir) {
    if ($_SERVER['REQUEST_METHOD']!=='POST'||!isset($_FILES['documents'])) return;
    $dir=rtrim($_SERVER['DOCUMENT_ROOT'],'/').'/'.trim($udir,'/').'/user_'.$uid.'/';
    if (!is_dir($dir)) @mkdir($dir,0775,true);
    $msgs=[]; $names=$_FILES['documents']['name']; $errs=$_FILES['documents']['error']; $sizes=$_FILES['documents']['size']; $tmps=$_FILES['documents']['tmp_name'];
    foreach ($names as $k=>$name) {
        if ($errs[$k]!==0) { $msgs[]='Error: '.h($name); continue; }
        $ext=strtolower(pathinfo($name,PATHINFO_EXTENSION));
        if (!in_array($ext,['pdf','jpg','jpeg','png'])) { $msgs[]='Invalid type: '.h($name); continue; }
        if ($sizes[$k]>5*1024*1024) { $msgs[]='Too large: '.h($name); continue; }
        $fn=date('Ymd_His').'_'.preg_replace('/[^a-zA-Z0-9._-]/','_',basename($name));
        $msgs[]=move_uploaded_file($tmps[$k],$dir.$fn) ? '✓ '.h($name) : '✗ Failed: '.h($name);
    }
    $_SESSION['flash_message']=['type'=>'success','html'=>implode(' | ',$msgs)];
    header('Location:manage_users.php'); exit;
}

// ── ROUTING ────────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['update_manager'])) updateReportingManager($conn);
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['bulk_employee_upload'])) handleEmployeeBulkUpload($conn);
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['bulk_employee_action'])) handleBulkEmployeeAction($conn,$upload_dir_rel);
if (isset($_GET['download_template'])) downloadEmployeeTemplate($conn);
if (isset($_GET['download_all']))      downloadAllEmployees($conn);
if (isset($_GET['upload']) && $_SERVER['REQUEST_METHOD']==='POST') handleDocumentsUpload($conn,$_GET['upload'],$upload_dir_rel);
if (isset($_GET['release']))           releaseAppointment($conn,$_GET['release'],$upload_dir_rel);
if (isset($_GET['mark_seen']))         markOfferSeen($conn,$_GET['mark_seen']);
if (isset($_GET['remove_letter']))     removeAppointment($conn,$_GET['remove_letter'],$upload_dir_rel);
if (isset($_GET['recreate']))          recreateAppointment($conn,$_GET['recreate'],$upload_dir_rel);
if (isset($_GET['resign']))            resignUser($conn,$_GET['resign']);
if (isset($_GET['restore']))           restoreUser($conn,$_GET['restore']);

// ── PAGE DATA ──────────────────────────────────────────────────────────────
ensureOfferColumns($conn);
$users        = fetchAllUsers($conn);
$deletedUsers = fetchDeletedUsers($conn);
$userMap      = fetchUserMap($conn);   // id => "Full Name" for all active non-superadmin

$total_released = count(array_filter($users, fn($u)=>!empty($u['offer_released'])&&$u['offer_released']==1));
$total_pending  = count($users)-$total_released;

$recentOffers=[];
$rO=$conn->query("SELECT id,username,first_name,last_name,offer_released_at,offer_accepted FROM users WHERE offer_released=1 AND offer_seen=0 ORDER BY offer_released_at DESC LIMIT 20");
if ($rO) $recentOffers=$rO->fetch_all(MYSQLI_ASSOC);

$desig_list=[];
$rD=$conn->query("SELECT DISTINCT designation FROM users WHERE designation IS NOT NULL AND designation!='' ORDER BY designation");
if ($rD) $desig_list=$rD->fetch_all(MYSQLI_ASSOC);

ob_end_flush();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">
<title>MPC · Manage Users</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Sora:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
:root{
  --ink:#0f172a;--ink2:#334155;--muted:#94a3b8;--border:#e2e8f0;--surface:#fff;--bg:#f1f5f9;
  --sidebar-bg:#0f172a;--sidebar-w:260px;
  --blue:#1d4ed8;--blue-l:#dbeafe;--green:#059669;--green-l:#d1fae5;
  --amber:#d97706;--amber-l:#fef3c7;--red:#dc2626;--red-l:#fee2e2;--violet:#7c3aed;--violet-l:#ede9fe;
  --teal:#0d9488;--teal-l:#ccfbf1;
  --r:12px;--shadow:0 1px 3px rgba(15,23,42,.06),0 4px 16px rgba(15,23,42,.06);
  font-family:'Sora',system-ui,sans-serif;
}
html,body{height:100%}
body{background:var(--bg);color:var(--ink);font-size:14px;line-height:1.6;-webkit-font-smoothing:antialiased}

/* LAYOUT */
.layout{display:flex;min-height:100vh}
.sidebar{width:var(--sidebar-w);background:var(--sidebar-bg);position:fixed;inset:0 auto 0 0;z-index:200;display:flex;flex-direction:column;overflow-y:auto;overflow-x:hidden;transition:transform .3s;scrollbar-width:none}
.sidebar::-webkit-scrollbar{display:none}
.sidebar.hidden{transform:translateX(-100%)}
.sidebar-brand{padding:24px 20px 16px;display:flex;align-items:center;gap:10px;border-bottom:1px solid rgba(255,255,255,.06);margin-bottom:8px}
.brand-logo{width:36px;height:36px;background:linear-gradient(135deg,#3b82f6,#6366f1);border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:16px;font-weight:700;color:#fff;flex-shrink:0}
.brand-name{font-size:15px;font-weight:700;color:#fff}
.brand-sub{font-size:10px;color:rgba(255,255,255,.4);letter-spacing:1.5px;text-transform:uppercase;margin-top:1px}
.nav-section{padding:0 12px 6px}
.nav-item{list-style:none}
.nav-link,.nav-dt{display:flex;align-items:center;gap:10px;padding:8px 10px;border-radius:8px;color:rgba(255,255,255,.65);text-decoration:none;font-size:13px;font-weight:500;cursor:pointer;border:none;background:none;width:100%;text-align:left;transition:background .15s,color .15s}
.nav-link:hover,.nav-dt:hover{background:rgba(255,255,255,.07);color:#fff}
.nav-link.active{background:rgba(59,130,246,.2);color:#60a5fa}
.nav-link i,.nav-dt i{width:16px;text-align:center;font-size:13px}
.arrow{margin-left:auto;transition:transform .2s;font-size:10px}
.nav-dt.open .arrow{transform:rotate(180deg)}
.nav-sub{list-style:none;overflow:hidden;max-height:0;transition:max-height .3s;padding-left:26px}
.nav-sub.open{max-height:600px}
.nav-sub .nav-link{font-size:12px;padding:6px 10px;color:rgba(255,255,255,.5)}
.nav-sub .nav-link:hover{color:#fff;background:rgba(255,255,255,.05)}
.sidebar-footer{margin-top:auto;padding:12px;border-top:1px solid rgba(255,255,255,.06)}
.content{flex:1;margin-left:var(--sidebar-w);min-width:0;display:flex;flex-direction:column;transition:margin .3s}
.content.expanded{margin-left:0}
.topbar{height:60px;background:var(--surface);border-bottom:1px solid var(--border);display:flex;align-items:center;gap:12px;padding:0 24px;position:sticky;top:0;z-index:100}
.hbtn{width:36px;height:36px;border-radius:8px;border:1px solid var(--border);background:var(--surface);display:flex;align-items:center;justify-content:center;cursor:pointer;color:var(--ink2);font-size:15px;transition:background .15s}
.hbtn:hover{background:var(--bg)}
.breadcrumb{display:flex;align-items:center;gap:6px;font-size:13px;color:var(--muted)}
.breadcrumb .cur{color:var(--ink);font-weight:600}
.t-spacer{flex:1}
.t-user{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--ink2);font-weight:500}
.t-av{width:30px;height:30px;border-radius:50%;background:linear-gradient(135deg,#3b82f6,#6366f1);display:flex;align-items:center;justify-content:center;color:#fff;font-size:12px;font-weight:700}
.page{padding:24px;flex:1}
.ph{margin-bottom:20px;display:flex;align-items:flex-start;justify-content:space-between;flex-wrap:wrap;gap:12px}
.ph .title{font-size:22px;font-weight:700;letter-spacing:-.4px}
.ph .sub{font-size:13px;color:var(--muted);margin-top:2px}

/* STATS */
.stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:14px;margin-bottom:20px}
.sc{background:var(--surface);border:1px solid var(--border);border-radius:var(--r);padding:16px 18px;display:flex;align-items:center;gap:14px;box-shadow:var(--shadow)}
.si{width:42px;height:42px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:17px;flex-shrink:0}
.si.blue{background:var(--blue-l);color:var(--blue)}.si.green{background:var(--green-l);color:var(--green)}
.si.amber{background:var(--amber-l);color:var(--amber)}.si.red{background:var(--red-l);color:var(--red)}
.sl{font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:.7px;color:var(--muted)}
.sv{font-size:24px;font-weight:800;font-family:'JetBrains Mono',monospace;line-height:1.1}

/* CARD */
.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--r);box-shadow:var(--shadow);overflow:hidden;margin-bottom:20px}
.card-hdr{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px;padding:14px 20px;border-bottom:1px solid var(--border)}
.card-title{font-size:14px;font-weight:700;display:flex;align-items:center;gap:8px}
.card-body{padding:20px}

/* ALERT */
.alert{padding:12px 16px;border-radius:10px;font-size:13px;font-weight:500;display:flex;align-items:flex-start;gap:10px;margin-bottom:16px;border:1px solid transparent;animation:fadeUp .25s ease}
.alert-success{background:var(--green-l);border-color:#6ee7b7;color:#065f46}
.alert-danger{background:var(--red-l);border-color:#fca5a5;color:#991b1b}
.alert-close{margin-left:auto;cursor:pointer;background:none;border:none;font-size:18px;color:inherit;opacity:.5;line-height:1;flex-shrink:0}
.alert-close:hover{opacity:1}
@keyframes fadeUp{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}

/* BUTTONS */
.btn{display:inline-flex;align-items:center;gap:6px;padding:7px 14px;border-radius:8px;border:1px solid transparent;font-size:12px;font-weight:600;font-family:'Sora',sans-serif;cursor:pointer;text-decoration:none;transition:all .15s;white-space:nowrap;line-height:1}
.btn:hover{opacity:.88;transform:translateY(-1px)}
.btn:active{transform:translateY(0)}
.btn-primary{background:var(--blue);color:#fff;border-color:var(--blue)}
.btn-success{background:var(--green);color:#fff;border-color:var(--green)}
.btn-warning{background:var(--amber);color:#fff;border-color:var(--amber)}
.btn-danger{background:var(--red);color:#fff;border-color:var(--red)}
.btn-secondary{background:var(--ink);color:#fff;border-color:var(--ink)}
.btn-violet{background:var(--violet);color:#fff;border-color:var(--violet)}
.btn-teal{background:var(--teal);color:#fff;border-color:var(--teal)}
.btn-outline{background:var(--surface);color:var(--ink2);border-color:var(--border)}
.btn-outline:hover{background:var(--bg);border-color:#94a3b8}
.btn-sm{padding:5px 10px;font-size:11px;border-radius:6px}
.btn:disabled{opacity:.55;cursor:not-allowed;transform:none;pointer-events:none}

/* ACTION BAR */
.abar{display:flex;flex-wrap:wrap;gap:8px;margin-bottom:16px;align-items:center}

/* FILTER BAR */
.fbar{display:flex;flex-wrap:wrap;gap:10px;align-items:flex-end;padding:14px 20px;border-bottom:1px solid var(--border);background:var(--bg)}
.fg{display:flex;flex-direction:column;gap:4px}
.fg.grow{flex:1;min-width:160px}
.fl{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.8px;color:var(--muted)}
.fi,.fs{height:36px;border:1px solid var(--border);border-radius:8px;padding:0 10px;font-size:13px;font-family:'Sora',sans-serif;color:var(--ink);background:var(--surface);outline:none;transition:border-color .15s,box-shadow .15s;min-width:130px}
.fi:focus,.fs:focus{border-color:#3b82f6;box-shadow:0 0 0 3px rgba(59,130,246,.12)}

/* TABLE */
.tw{overflow-x:auto}
table{width:100%;border-collapse:collapse;font-size:13px}
thead th{background:var(--ink);color:rgba(255,255,255,.85);font-weight:600;font-size:11px;text-transform:uppercase;letter-spacing:.8px;padding:11px 14px;text-align:left;white-space:nowrap}
tbody td{padding:10px 14px;border-bottom:1px solid var(--border);color:var(--ink2);vertical-align:middle}
tbody tr:last-child td{border-bottom:none}
tbody tr:hover td{background:#f8fafc}
.sno{font-family:'JetBrains Mono',monospace;color:var(--muted);font-size:12px}
.emp-thumb{width:36px;height:36px;border-radius:50%;object-fit:cover;border:2px solid var(--border);display:block}
.av{width:36px;height:36px;border-radius:50%;border:2px solid var(--border);background:linear-gradient(135deg,#3b82f6,#6366f1);display:flex;align-items:center;justify-content:center;font-size:14px;font-weight:700;color:#fff;flex-shrink:0}

/* BADGES */
.badge{display:inline-flex;align-items:center;gap:4px;padding:3px 10px;border-radius:20px;font-size:11px;font-weight:600;white-space:nowrap}
.b-active{background:var(--green-l);color:#065f46}.b-resigned{background:var(--red-l);color:#991b1b}
.b-released{background:var(--blue-l);color:#1e40af}.b-pending{background:var(--amber-l);color:#92400e}
.b-accepted{background:var(--green-l);color:#065f46}.b-unseen{background:var(--amber-l);color:#92400e}
.cb{background:var(--bg);border:1px solid var(--border);border-radius:20px;padding:2px 10px;font-size:11px;font-weight:700;color:var(--muted);font-family:'JetBrains Mono',monospace}

/* REPORTING MANAGER MODAL */
.modal-overlay{position:fixed;inset:0;background:rgba(15,23,42,.45);z-index:500;display:flex;align-items:center;justify-content:center;padding:20px;opacity:0;pointer-events:none;transition:opacity .2s}
.modal-overlay.open{opacity:1;pointer-events:all}
.modal{background:var(--surface);border-radius:16px;width:100%;max-width:480px;box-shadow:0 20px 60px rgba(15,23,42,.2);transform:translateY(16px);transition:transform .25s;overflow:hidden}
.modal-overlay.open .modal{transform:translateY(0)}
.modal-hdr{padding:18px 22px 14px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between}
.modal-title{font-size:15px;font-weight:700;display:flex;align-items:center;gap:8px}
.modal-close{width:30px;height:30px;border-radius:8px;border:1px solid var(--border);background:none;cursor:pointer;font-size:16px;color:var(--muted);display:flex;align-items:center;justify-content:center;transition:background .15s}
.modal-close:hover{background:var(--bg);color:var(--ink)}
.modal-body{padding:20px 22px}
.modal-footer{padding:14px 22px;border-top:1px solid var(--border);display:flex;gap:8px;justify-content:flex-end}
.form-group{margin-bottom:16px}
.form-label{display:block;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.8px;color:var(--muted);margin-bottom:6px}
.form-control{width:100%;height:40px;border:1px solid var(--border);border-radius:8px;padding:0 12px;font-size:13px;font-family:'Sora',sans-serif;color:var(--ink);background:var(--surface);outline:none;transition:border-color .15s,box-shadow .15s}
.form-control:focus{border-color:#3b82f6;box-shadow:0 0 0 3px rgba(59,130,246,.12)}
.manager-badge{display:inline-flex;align-items:center;gap:6px;padding:4px 12px;background:var(--teal-l);color:#0f766e;border-radius:20px;font-size:12px;font-weight:600}
.manager-none{display:inline-flex;align-items:center;gap:5px;padding:4px 10px;background:var(--bg);color:var(--muted);border-radius:20px;font-size:11px;font-weight:600;border:1px dashed var(--border)}

/* OFFER */
.oi{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px;padding:14px 20px;border-bottom:1px solid var(--border)}
.oi:last-child{border-bottom:none}
.oi-name{font-size:13px;font-weight:700;color:var(--ink)}
.oi-meta{font-size:11px;color:var(--muted);margin-top:2px}
.oa{display:flex;flex-wrap:wrap;gap:5px;align-items:center;flex-shrink:0}
.oi-hidden{display:none}
.smbar{padding:12px 20px;text-align:center;border-top:1px solid var(--border)}
.smbtn{background:none;border:1px solid var(--border);border-radius:8px;padding:6px 16px;font-size:12px;font-weight:600;font-family:'Sora',sans-serif;color:var(--ink2);cursor:pointer;transition:background .15s}
.smbtn:hover{background:var(--bg)}

/* UPLOAD PANEL */
.up-panel{background:#eff6ff;border:1.5px dashed #93c5fd;border-radius:var(--r);padding:20px;margin-bottom:20px}
.up-panel h5{font-size:14px;font-weight:700;color:#1e40af;margin-bottom:12px}
.file-input{width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:8px;font-size:13px;font-family:'Sora',sans-serif;background:var(--surface);color:var(--ink);margin-bottom:12px}
.docs-list{list-style:none;display:flex;flex-direction:column;gap:6px}
.docs-list li{padding:10px 14px;background:var(--bg);border:1px solid var(--border);border-radius:8px;display:flex;align-items:center;gap:8px}
.docs-list li i{color:var(--red);font-size:14px}
.docs-list li a{font-size:13px;color:var(--blue);text-decoration:none;font-weight:500}
.docs-list li a:hover{text-decoration:underline}
.ac{display:flex;flex-wrap:wrap;gap:4px;align-items:center}
.empty{text-align:center;padding:48px 20px;color:var(--muted)}
.empty i{font-size:36px;margin-bottom:12px;display:block}
.empty p{font-size:13px}
.tfoot{padding:10px 20px;border-top:1px solid var(--border);background:var(--bg);font-size:12px;color:var(--muted)}

/* TOOLTIP */
[data-tip]{position:relative}
[data-tip]::after{content:attr(data-tip);position:absolute;bottom:calc(100% + 6px);left:50%;transform:translateX(-50%);background:var(--ink);color:#fff;font-size:11px;padding:4px 8px;border-radius:6px;white-space:nowrap;opacity:0;pointer-events:none;transition:opacity .15s;z-index:99}
[data-tip]:hover::after{opacity:1}

/* Manager search in select */
.manager-search-wrap{position:relative}
.manager-search-input{width:100%;height:36px;border:1px solid var(--border);border-radius:8px 8px 0 0;padding:0 12px 0 34px;font-size:13px;font-family:'Sora',sans-serif;color:var(--ink);background:var(--surface);outline:none;border-bottom:none}
.manager-search-icon{position:absolute;left:10px;top:50%;transform:translateY(-50%);color:var(--muted);font-size:12px;pointer-events:none}
.manager-select{border-radius:0 0 8px 8px;border-top:1px solid var(--border)}
.manager-select option{padding:6px}

@media(max-width:768px){
  .sidebar{transform:translateX(-100%)}.sidebar:not(.hidden){transform:none}
  .content{margin-left:0}.page{padding:14px}
  .oi{flex-direction:column;align-items:flex-start}
  .stats{grid-template-columns:1fr 1fr}
  .modal{max-width:100%}
}
@media(max-width:480px){.stats{grid-template-columns:1fr}}
</style>
</head>
<body>
<div class="layout">

<!-- SIDEBAR -->
<nav class="sidebar" id="sidebar">
  <div class="sidebar-brand">
    <div class="brand-logo">M</div>
    <div><div class="brand-name">MPC</div><div class="brand-sub">Admin Portal</div></div>
  </div>
  <nav class="nav-section">
    <ul style="list-style:none">
      <li class="nav-item"><a href="dashboard_admin.php" class="nav-link"><i class="fas fa-sitemap"></i> Organisation Chart</a></li>
      <li class="nav-item">
        <button class="nav-dt open" onclick="toggleMenu(this)"><i class="fas fa-folder-open"></i> DAP<i class="fas fa-chevron-down arrow"></i></button>
        <ul class="nav-sub open">
          <li><a href="manage_users.php"     class="nav-link active"><i class="fas fa-users"></i>        Employee Details</a></li>
          <li><a href="manage_documents.php" class="nav-link"><i class="fas fa-file-alt"></i>     Policies Rolled Out</a></li>
          <li><a href="digital.php"          class="nav-link"><i class="fas fa-check-circle"></i> Acceptance Confirmed</a></li>
          <li><a href="change_password.php"  class="nav-link"><i class="fas fa-key"></i>          Change Password</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dt" onclick="toggleMenu(this)"><i class="fas fa-calendar-alt"></i> CAB<i class="fas fa-chevron-down arrow"></i></button>
        <ul class="nav-sub">
          <li><a href="attendance.php"              class="nav-link"><i class="fas fa-clock"></i>             Attendance Dashboard</a></li>
          <li><a href="payroll.php"                 class="nav-link"><i class="fas fa-money-bill"></i>        Payroll Dashboard</a></li>
          <li><a href="mobile_attendance.php"       class="nav-link"><i class="fas fa-mobile-alt"></i>       Daily Attendance Report</a></li>
          <li><a href="task_dashboard.php"          class="nav-link"><i class="fas fa-tasks"></i>            Task Dashboard</a></li>
          <li><a href="daily_reports_dashboard.php" class="nav-link"><i class="fas fa-chart-line"></i>       Daily Report Dashboard</a></li>
          <li><a href="company_holidays.php"        class="nav-link"><i class="fas fa-star"></i>             Company Holidays</a></li>
          <li><a href="hr_approval_salary.php"      class="nav-link"><i class="fas fa-hand-holding-usd"></i> Advance Dashboard</a></li>
          <li><a href="expense_dashboard.php"       class="nav-link"><i class="fas fa-receipt"></i>          Expenses Dashboard</a></li>
          <li><a href="leave_dashboard.php"         class="nav-link"><i class="fas fa-umbrella-beach"></i>   Leave Dashboard</a></li>
          <li><a href="grievance_dashboard.php"     class="nav-link"><i class="fas fa-comment-alt"></i>      Grievance Dashboard</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dt" onclick="toggleMenu(this)"><i class="fas fa-user-tie"></i> PEP<i class="fas fa-chevron-down arrow"></i></button>
        <ul class="nav-sub">
          <li><a href="individual_rr.php"  class="nav-link"><i class="fas fa-trophy"></i>   Individual R &amp; R</a></li>
          <li><a href="individual_kpi.php" class="nav-link"><i class="fas fa-bullseye"></i> Individual KPI</a></li>
          <li><a href="https://spica.mypeopleconnect.app/" class="nav-link"><i class="fas fa-id-card"></i> PEP Login</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dt" onclick="toggleMenu(this)"><i class="fas fa-book-open"></i> L&amp;D<i class="fas fa-chevron-down arrow"></i></button>
        <ul class="nav-sub">
          <li><a href="incident_employee.php"  class="nav-link"><i class="fas fa-exclamation-triangle"></i> Incident Portal</a></li>
          <li><a href="training_dashboard.php" class="nav-link"><i class="fas fa-chalkboard-teacher"></i>   Training Portal</a></li>
          <li><a href="rr.php"                 class="nav-link"><i class="fas fa-award"></i>                Rewards &amp; Recognition</a></li>
        </ul>
      </li>
      <li class="nav-item">
        <button class="nav-dt" onclick="toggleMenu(this)"><i class="fas fa-star"></i> AAA<i class="fas fa-chevron-down arrow"></i></button>
        <ul class="nav-sub">
          <li><a href="employee_tiy.php"      class="nav-link"><i class="fas fa-user-check"></i> Employee TIY</a></li>
          <li><a href="login_credentials.php" class="nav-link"><i class="fas fa-id-card"></i>    Login Credentials</a></li>
        </ul>
      </li>
    </ul>
  </nav>
  <div class="sidebar-footer">
    <a href="logout.php" class="nav-link" style="color:#f87171"><i class="fas fa-sign-out-alt"></i> Logout</a>
  </div>
</nav>

<!-- CONTENT -->
<div class="content" id="content">
  <div class="topbar">
    <button class="hbtn" onclick="toggleSidebar()"><i class="fas fa-bars"></i></button>
    <div class="breadcrumb"><span>DAP</span><i class="fas fa-chevron-right" style="font-size:10px;color:var(--border)"></i><span class="cur">Employee Details</span></div>
    <div class="t-spacer"></div>
    <div class="t-user">
      <div class="t-av"><?php echo strtoupper(substr($username_session?:'A',0,1)); ?></div>
      <?php echo h($username_session?:'Admin'); ?>
    </div>
  </div>

  <div class="page">

    <!-- Page Header -->
    <div class="ph">
      <div><div class="title">Manage Users</div><div class="sub">Employee records · appointment letters · reporting managers · status management</div></div>
    </div>

    <!-- Flash -->
    <?php if (!empty($_SESSION['flash_message'])): $fm=$_SESSION['flash_message']; $t=$fm['type']??'info'; $ic=($t==='success')?'check-circle':(($t==='danger')?'exclamation-circle':'info-circle'); ?>
    <div class="alert alert-<?php echo h($t); ?>" id="flashMsg">
      <i class="fas fa-<?php echo $ic; ?>"></i><span><?php echo $fm['html']; ?></span>
      <button class="alert-close" onclick="this.closest('.alert').remove()">×</button>
    </div>
    <?php unset($_SESSION['flash_message']); endif; ?>

    <!-- Stats -->
    <div class="stats">
      <div class="sc"><div class="si blue"><i class="fas fa-users"></i></div><div><div class="sl">Active</div><div class="sv"><?php echo count($users); ?></div></div></div>
      <div class="sc"><div class="si green"><i class="fas fa-paper-plane"></i></div><div><div class="sl">Letters Released</div><div class="sv"><?php echo $total_released; ?></div></div></div>
      <div class="sc"><div class="si amber"><i class="fas fa-clock"></i></div><div><div class="sl">Pending Letter</div><div class="sv"><?php echo $total_pending; ?></div></div></div>
      <div class="sc"><div class="si red"><i class="fas fa-user-slash"></i></div><div><div class="sl">Resigned</div><div class="sv"><?php echo count($deletedUsers); ?></div></div></div>
    </div>

    <!-- Action Bar -->
    <div class="abar">
      <a class="btn btn-primary" href="create_user_form.php"><i class="fas fa-user-plus"></i> Create New User</a>
      <a class="btn btn-success" href="manage_users.php?download_all=1"><i class="fas fa-file-excel"></i> Download All (CSV)</a>
      <a class="btn btn-teal" href="manage_users.php?download_template=1"><i class="fas fa-file-arrow-down"></i> Download Upload Template</a>
      <a class="btn btn-violet" href="manage_users.php?bulk_upload=1"><i class="fas fa-file-import"></i> Bulk Upload</a>
    </div>

    <?php if (isset($_GET['bulk_upload'])): ?>
    <div class="up-panel">
      <h5><i class="fas fa-file-import" style="margin-right:6px"></i>Bulk Upload Employees</h5>
      <form method="post" enctype="multipart/form-data" action="manage_users.php">
        <input type="hidden" name="bulk_employee_upload" value="1">
        <label class="fl" style="display:block;margin-bottom:6px">Upload CSV saved from Excel template</label>
        <input type="file" name="employee_excel" accept=".csv,text/csv" class="file-input" required>
        <div style="display:flex;gap:8px;flex-wrap:wrap;margin-top:4px">
          <button class="btn btn-primary" type="submit"><i class="fas fa-cloud-upload-alt"></i> Upload Employees</button>
          <a class="btn btn-outline" href="manage_users.php?download_template=1"><i class="fas fa-file-arrow-down"></i> Download Template</a>
          <a class="btn btn-outline" href="manage_users.php"><i class="fas fa-times"></i> Cancel</a>
        </div>
        <p style="font-size:12px;color:var(--muted);margin-top:10px">Existing employee id/username will be updated. New employees will be inserted. Department/Designation names are matched from divisions/departments and designations table.</p>
      </form>
    </div>
    <?php endif; ?>

    <!-- RECENT UNSEEN OFFERS -->
    <?php if (!empty($recentOffers)): ?>
    <div class="card">
      <div class="card-hdr">
        <div class="card-title"><i class="fas fa-bell" style="color:var(--amber)"></i> Recently Released — Awaiting Employee View <span style="background:var(--red);color:#fff;border-radius:20px;padding:1px 9px;font-size:11px;font-weight:700"><?php echo count($recentOffers); ?></span></div>
      </div>
      <div id="offerList">
        <?php foreach ($recentOffers as $idx=>$o):
          $uid=h($o['id']); $name=empName($o);
          $furl='/'.ltrim(trim($upload_dir_rel,'/').'/user_'.$o['id'].'/appointment_letter.pdf','/');
          $fabs=rtrim($_SERVER['DOCUMENT_ROOT'],'/').'/'.trim($upload_dir_rel,'/').'/user_'.$o['id'].'/appointment_letter.pdf';
          $fok=file_exists($fabs)&&is_readable($fabs);
          $acc=$o['offer_accepted']??'Pending';
        ?>
        <div class="oi <?php echo $idx>=3?'oi-hidden':''; ?>">
          <div>
            <div class="oi-name"><?php echo h($name); ?></div>
            <div class="oi-meta">Released: <?php echo h($o['offer_released_at']??'—'); ?> · Status: <span class="badge <?php echo $acc==='Accepted'?'b-accepted':'b-pending'; ?>"><?php echo h($acc); ?></span></div>
          </div>
          <div class="oa">
            <?php if ($fok): ?><a class="btn btn-sm btn-primary" href="<?php echo h($furl); ?>" target="_blank" data-tip="View PDF"><i class="fas fa-eye"></i></a><?php endif; ?>
            <a class="btn btn-sm btn-warning" href="manage_users.php?recreate=<?php echo urlencode($o['id']); ?>" onclick="return confirm('Regenerate letter for <?php echo h($name); ?>?')" data-tip="Update Letter"><i class="fas fa-redo"></i></a>
            <a class="btn btn-sm btn-secondary" href="manage_users.php?mark_seen=<?php echo urlencode($o['id']); ?>" onclick="return confirm('Mark as seen?')" data-tip="Mark Seen"><i class="fas fa-eye-slash"></i></a>
            <a class="btn btn-sm btn-danger" href="manage_users.php?remove_letter=<?php echo urlencode($o['id']); ?>" onclick="return confirm('Remove letter for <?php echo h($name); ?>?')" data-tip="Remove"><i class="fas fa-trash"></i></a>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
      <?php if (count($recentOffers)>3): ?>
      <div class="smbar"><button class="smbtn" id="toggleMoreOffers"><i class="fas fa-chevron-down" style="margin-right:4px"></i>Show <?php echo count($recentOffers)-3; ?> more</button></div>
      <?php endif; ?>
    </div>
    <?php endif; ?>

    <!-- ACTIVE EMPLOYEES TABLE -->
    <div class="card">
      <div class="card-hdr">
        <div class="card-title"><i class="fas fa-users"></i> Active Employees</div>
        <span class="cb" id="activeCount"><?php echo count($users); ?> employees</span>
      </div>
      <div class="fbar">
        <div class="fg grow"><span class="fl">Name</span><input type="text" id="fName" class="fi" placeholder="Filter by name…" oninput="filterTable()"></div>
        <div class="fg"><span class="fl">Employee ID</span><input type="text" id="fId" class="fi" placeholder="User ID…" oninput="filterTable()"></div>
        <div class="fg">
          <span class="fl">Designation</span>
          <select id="fDesig" class="fs" onchange="filterTable()">
            <option value="">All</option>
            <?php foreach ($desig_list as $d): ?><option value="<?php echo h($d['designation']); ?>"><?php echo h($d['designation']); ?></option><?php endforeach; ?>
          </select>
        </div>
        <div class="fg">
          <span class="fl">Letter</span>
          <select id="fLetter" class="fs" onchange="filterTable()">
            <option value="">All</option><option value="released">Released</option><option value="pending">Pending</option>
          </select>
        </div>
        <div class="fg">
          <span class="fl">Manager</span>
          <input type="text" id="fManager" class="fi" placeholder="Manager name…" oninput="filterTable()">
        </div>
        <div class="fg"><button class="btn btn-outline btn-sm" onclick="clearFilters()" style="margin-top:18px"><i class="fas fa-times"></i> Clear</button></div>
      </div>
      <form method="post" action="manage_users.php" id="bulkActionForm">
        <input type="hidden" name="bulk_employee_action" value="1">
        <div class="fbar" style="border-top:1px solid var(--border);border-bottom:1px solid var(--border)">
          <div class="fg">
            <span class="fl">With Selected</span>
            <select name="bulk_action" class="fs" required>
              <option value="">Choose Action</option>
              <option value="release_letters">Release Appointment Letters</option>
              <option value="mark_seen">Mark Letters Seen</option>
              <option value="remove_letters">Remove Letters</option>
              <option value="resign">Mark as Resigned</option>
            </select>
          </div>
          <div class="fg"><button type="submit" class="btn btn-secondary btn-sm" style="margin-top:18px" onclick="return confirm('Apply selected bulk action?')"><i class="fas fa-check-double"></i> Apply</button></div>
        </div>
      <div class="tw">
        <table id="usersTable">
          <thead>
            <tr>
              <th style="width:36px"><input type="checkbox" id="checkAllUsers" onclick="toggleAllUsers(this)"></th>
              <th style="width:44px">#</th>
              <th style="width:52px">Photo</th>
              <th>Name</th>
              <th>ID</th>
              <th>Designation</th>
              <th>Company</th>
              <th>Reporting Manager</th>
              <th>Letter</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($users as $i=>$u):
              $uid=$u['id']; $ename=empName($u);
              $released=!empty($u['offer_released'])&&$u['offer_released']==1;
              $furl='/'.ltrim(trim($upload_dir_rel,'/').'/user_'.$uid.'/appointment_letter.pdf','/');
              $fabs=rtrim($_SERVER['DOCUMENT_ROOT'],'/').'/'.trim($upload_dir_rel,'/').'/user_'.$uid.'/appointment_letter.pdf';
              $fok=$released&&file_exists($fabs)&&is_readable($fabs);
              $acc=$u['offer_accepted']??'Pending';
              // Resolve manager name
              $managerName = resolveManagerName($conn, $u, $userMap);
              $managerId   = trim($u['reporting_manager_id'] ?? '');
            ?>
            <tr
              data-name="<?php echo h(strtolower($ename)); ?>"
              data-id="<?php echo h(strtolower($uid)); ?>"
              data-desig="<?php echo h(strtolower($u['designation']??'')); ?>"
              data-letter="<?php echo $released?'released':'pending'; ?>"
              data-manager="<?php echo h(strtolower($managerName)); ?>"
            >
              <td><input type="checkbox" name="selected_users[]" value="<?php echo h($uid); ?>" class="rowCheck"></td>
              <td class="sno"><?php echo $i+1; ?></td>
              <td><?php echo user_photo_tag($u['photo']??'',$upload_dir_rel,$default_photo,h($ename),36,36); ?></td>
              <td>
                <div style="font-weight:600;color:var(--ink)"><?php echo h($ename); ?></div>
                <div style="font-size:11px;color:var(--muted)"><?php echo h($u['division']??''); ?></div>
              </td>
              <td style="font-family:'JetBrains Mono',monospace;font-size:12px;color:var(--muted)"><?php echo h($uid); ?></td>
              <td>
                <div style="color:var(--ink2);font-size:12px"><?php echo h($u['designation']??'—'); ?></div>
                <div style="font-size:11px;color:var(--muted)"><?php echo h($u['level']??''); ?></div>
              </td>
              <td style="font-size:12px;color:var(--ink2)"><?php echo h($u['Company']??'—'); ?></td>
              <td>
                <?php if ($managerName !== ''): ?>
                  <div class="manager-badge" style="margin-bottom:4px">
                    <i class="fas fa-user-tie" style="font-size:10px"></i>
                    <?php echo h($managerName); ?>
                  </div>
                  <?php if ($managerId !== ''): ?>
                    <div style="font-size:10px;color:var(--muted);font-family:'JetBrains Mono',monospace"><?php echo h($managerId); ?></div>
                  <?php endif; ?>
                <?php else: ?>
                  <span class="manager-none"><i class="fas fa-minus" style="font-size:9px"></i> Not assigned</span>
                <?php endif; ?>
                <button
                  class="btn btn-sm btn-teal"
                  style="margin-top:6px"
                  onclick="openManagerModal('<?php echo h(addslashes($uid)); ?>','<?php echo h(addslashes($ename)); ?>','<?php echo h(addslashes($managerId)); ?>')"
                  data-tip="Set Reporting Manager"
                >
                  <i class="fas fa-<?php echo $managerName!==''?'edit':'plus'; ?>"></i> <?php echo $managerName!==''?'Change':'Assign'; ?>
                </button>
              </td>
              <td>
                <?php if ($released): ?>
                  <span class="badge b-released"><i class="fas fa-check" style="font-size:9px"></i> Released</span>
                  <?php if ($acc==='Accepted'): ?><br><span class="badge b-accepted" style="margin-top:3px;font-size:10px"><i class="fas fa-thumbs-up" style="font-size:9px"></i> Accepted</span>
                  <?php elseif (!empty($u['offer_seen'])&&$u['offer_seen']==1): ?><br><span class="badge" style="margin-top:3px;font-size:10px;background:#f1f5f9;color:var(--ink2)"><i class="fas fa-eye" style="font-size:9px"></i> Seen</span>
                  <?php else: ?><br><span class="badge b-unseen" style="margin-top:3px;font-size:10px"><i class="fas fa-eye-slash" style="font-size:9px"></i> Unseen</span>
                  <?php endif; ?>
                <?php else: ?><span class="badge b-pending"><i class="fas fa-minus" style="font-size:9px"></i> Pending</span><?php endif; ?>
              </td>
              <td>
                <div class="ac">
                  <a class="btn btn-sm btn-outline" href="view_user_details.php?id=<?php echo urlencode($uid); ?>" data-tip="View"><i class="fas fa-eye"></i></a>
                  <a class="btn btn-sm btn-outline" href="download_user_details.php?id=<?php echo urlencode($uid); ?>" data-tip="Download Profile"><i class="fas fa-download"></i></a>
                  <?php if ($fok): ?><a class="btn btn-sm btn-outline" href="<?php echo h($furl); ?>" target="_blank" data-tip="View Letter"><i class="fas fa-file-pdf" style="color:var(--red)"></i></a><?php endif; ?>
                  <?php if (!$released): ?>
                    <a class="btn btn-sm btn-success" href="manage_users.php?release=<?php echo urlencode($uid); ?>" onclick="return confirm('Release letter for <?php echo h($ename); ?>?')" data-tip="Release Letter"><i class="fas fa-paper-plane"></i> Release</a>
                  <?php else: ?>
                    <a class="btn btn-sm btn-warning" href="manage_users.php?recreate=<?php echo urlencode($uid); ?>" onclick="return confirm('Regenerate letter for <?php echo h($ename); ?>?')" data-tip="Update Letter"><i class="fas fa-redo"></i></a>
                    <a class="btn btn-sm btn-secondary" href="manage_users.php?mark_seen=<?php echo urlencode($uid); ?>" onclick="return confirm('Mark as seen?')" data-tip="Mark Seen"><i class="fas fa-eye-slash"></i></a>
                    <a class="btn btn-sm btn-danger" href="manage_users.php?remove_letter=<?php echo urlencode($uid); ?>" onclick="return confirm('Remove letter for <?php echo h($ename); ?>?')" data-tip="Remove Letter"><i class="fas fa-trash"></i></a>
                  <?php endif; ?>
                  <a class="btn btn-sm btn-outline" href="manage_users.php?upload=<?php echo urlencode($uid); ?>" data-tip="Upload Docs"><i class="fas fa-upload"></i></a>
                  <a class="btn btn-sm btn-outline" href="manage_users.php?view_docs=<?php echo urlencode($uid); ?>" data-tip="View Docs"><i class="fas fa-folder-open"></i></a>
                  <a class="btn btn-sm btn-danger" href="manage_users.php?resign=<?php echo urlencode($uid); ?>" onclick="return confirm('Resign <?php echo h($ename); ?>?')" data-tip="Resign"><i class="fas fa-user-minus"></i></a>
                </div>
              </td>
            </tr>
            <?php endforeach; ?>
            <?php if (empty($users)): ?><tr><td colspan="10"><div class="empty"><i class="fas fa-users-slash"></i><p>No active employees found.</p></div></td></tr><?php endif; ?>
          </tbody>
        </table>
      </div>
      <div class="tfoot" id="tableFooter">Showing all <?php echo count($users); ?> employees</div>
      </form>
    </div>

    <!-- RESIGNED TABLE -->
    <div class="card">
      <div class="card-hdr">
        <div class="card-title"><i class="fas fa-user-slash"></i> Resigned / Deleted Employees</div>
        <span class="cb"><?php echo count($deletedUsers); ?> records</span>
      </div>
      <?php if (empty($deletedUsers)): ?>
      <div class="empty"><i class="fas fa-check-circle" style="color:var(--green)"></i><p>No resigned or deleted employees.</p></div>
      <?php else: ?>
      <div class="tw">
        <table>
          <thead><tr><th>#</th><th>Photo</th><th>Name</th><th>ID</th><th>Role</th><th>Status</th><th>Resigned</th><th>Mobile</th><th>Actions</th></tr></thead>
          <tbody>
            <?php foreach ($deletedUsers as $i=>$u):
              $ename=empName($u); $us=strtolower($u['status']??'');
              $bc=($us==='resigned')?'b-resigned':'b-active';
            ?>
            <tr>
              <td class="sno"><?php echo $i+1; ?></td>
              <td><?php echo user_photo_tag($u['photo']??'',$upload_dir_rel,$default_photo,h($ename),36,36); ?></td>
              <td><div style="font-weight:600;color:var(--ink)"><?php echo h($ename); ?></div><div style="font-size:11px;color:var(--muted)"><?php echo h($u['designation']??''); ?></div></td>
              <td style="font-family:'JetBrains Mono',monospace;font-size:12px;color:var(--muted)"><?php echo h($u['id']); ?></td>
              <td style="font-size:12px;color:var(--ink2)"><?php echo h($u['role']); ?></td>
              <td><span class="badge <?php echo $bc; ?>"><?php echo h($u['status']); ?></span></td>
              <td style="font-size:12px;color:var(--ink2)"><?php echo h($u['resignation_date']??'—'); ?></td>
              <td style="font-size:12px;color:var(--ink2)"><?php echo h($u['mobileno']??'—'); ?></td>
              <td>
                <div class="ac">
                  <a class="btn btn-sm btn-outline" href="view_user_details.php?id=<?php echo urlencode($u['id']); ?>"><i class="fas fa-eye"></i></a>
                  <a class="btn btn-sm btn-success" href="manage_users.php?restore=<?php echo urlencode($u['id']); ?>" onclick="return confirm('Restore <?php echo h($ename); ?>?')"><i class="fas fa-user-check"></i> Restore</a>
                </div>
              </td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
      <?php endif; ?>
    </div>

    <!-- UPLOAD DOCS PANEL -->
    <?php if (isset($_GET['upload'])):
      $uuid=$_GET['upload']; $urow=fetchUser($conn,$uuid);
      $uname=$urow?empName($urow):$uuid;
    ?>
    <div class="up-panel">
      <h5><i class="fas fa-upload" style="margin-right:6px"></i>Upload Documents — <?php echo h($uname); ?> (ID: <?php echo h($uuid); ?>)</h5>
      <form method="post" enctype="multipart/form-data" action="manage_users.php?upload=<?php echo urlencode($uuid); ?>">
        <label class="fl" style="display:block;margin-bottom:6px">PDF / Image files — max 5 MB each</label>
        <input type="file" name="documents[]" multiple accept="application/pdf,image/jpeg,image/png" class="file-input">
        <div style="display:flex;gap:8px;margin-top:4px">
          <button class="btn btn-primary" type="submit"><i class="fas fa-cloud-upload-alt"></i> Upload</button>
          <a class="btn btn-outline" href="manage_users.php"><i class="fas fa-times"></i> Cancel</a>
        </div>
      </form>
    </div>
    <?php endif; ?>

    <!-- VIEW DOCS PANEL -->
    <?php if (isset($_GET['view_docs'])):
      $vuid=$_GET['view_docs']; $vrow=fetchUser($conn,$vuid); $vname=$vrow?empName($vrow):$vuid;
      $vdir=rtrim($_SERVER['DOCUMENT_ROOT'],'/').'/'.trim($upload_dir_rel,'/').'/user_'.$vuid.'/';
      $vbase='/'.trim($upload_dir_rel,'/').'/user_'.$vuid.'/';
    ?>
    <div class="card">
      <div class="card-hdr">
        <div class="card-title"><i class="fas fa-folder-open"></i> Documents — <?php echo h($vname); ?></div>
        <a class="btn btn-sm btn-outline" href="manage_users.php"><i class="fas fa-times"></i> Close</a>
      </div>
      <div class="card-body">
        <?php
        if (is_dir($vdir)) {
            $files=array_values(array_diff(scandir($vdir),['.','..']));
            if ($files) {
                echo '<ul class="docs-list">';
                foreach ($files as $f) {
                    $ext=strtolower(pathinfo($f,PATHINFO_EXTENSION));
                    $ic=in_array($ext,['jpg','jpeg','png'])?'fa-file-image':'fa-file-pdf';
                    $sz=round(filesize($vdir.$f)/1024,1);
                    echo "<li><i class='fas {$ic}'></i><a href='".h($vbase.rawurlencode($f))."' target='_blank'>".h($f)."</a><span style='margin-left:auto;font-size:11px;color:var(--muted)'>{$sz} KB</span></li>";
                }
                echo '</ul>';
            } else echo '<p style="color:var(--muted);font-size:13px">No documents uploaded yet.</p>';
        } else echo '<p style="color:var(--muted);font-size:13px">No documents uploaded yet.</p>';
        ?>
      </div>
    </div>
    <?php endif; ?>

  </div><!-- /.page -->
</div><!-- /.content -->
</div><!-- /.layout -->

<!-- ── REPORTING MANAGER MODAL ──────────────────────────────────────────── -->
<div class="modal-overlay" id="managerModal" onclick="closeManagerModalOutside(event)">
  <div class="modal" role="dialog" aria-modal="true" aria-labelledby="mmTitle">
    <div class="modal-hdr">
      <div class="modal-title" id="mmTitle"><i class="fas fa-user-tie" style="color:var(--teal)"></i> Assign Reporting Manager</div>
      <button class="modal-close" onclick="closeManagerModal()" aria-label="Close">×</button>
    </div>
    <form method="post" action="manage_users.php" id="managerForm">
      <input type="hidden" name="update_manager" value="1">
      <input type="hidden" name="emp_id" id="mmEmpId">
      <div class="modal-body">
        <div style="background:var(--bg);border:1px solid var(--border);border-radius:8px;padding:12px 14px;margin-bottom:16px">
          <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.8px;color:var(--muted);margin-bottom:3px">Assigning for</div>
          <div style="font-size:14px;font-weight:700;color:var(--ink)" id="mmEmpName">—</div>
        </div>
        <div class="form-group">
          <label class="form-label" for="mmSearch"><i class="fas fa-search" style="margin-right:4px"></i> Search Manager</label>
          <input type="text" id="mmSearch" class="form-control" placeholder="Type name to filter…" oninput="filterManagerOptions()" autocomplete="off">
        </div>
        <div class="form-group" style="margin-bottom:0">
          <label class="form-label" for="mmManagerId">Select Manager <span style="color:var(--muted);text-transform:none;letter-spacing:0;font-weight:500">(leave blank to remove assignment)</span></label>
          <select name="manager_id" id="mmManagerId" class="form-control" style="height:auto;padding:6px 10px;min-height:140px" size="7">
            <option value="">— No Manager (remove assignment) —</option>
            <?php foreach ($userMap as $mid => $mname): ?>
            <option value="<?php echo h($mid); ?>" data-name="<?php echo h(strtolower($mname)); ?>">
              <?php echo h($mname); ?> (<?php echo h($mid); ?>)
            </option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline" onclick="closeManagerModal()"><i class="fas fa-times"></i> Cancel</button>
        <button type="submit" class="btn btn-teal"><i class="fas fa-save"></i> Save Manager</button>
      </div>
    </form>
  </div>
</div>

<script>
// Sidebar
function toggleSidebar() {
  document.getElementById('sidebar').classList.toggle('hidden');
  document.getElementById('content').classList.toggle('expanded');
}
function toggleMenu(btn) {
  btn.classList.toggle('open');
  btn.nextElementSibling.classList.toggle('open');
}

// Auto-close flash
document.addEventListener('DOMContentLoaded', function() {
  var fm = document.getElementById('flashMsg');
  if (fm) setTimeout(function(){
    fm.style.transition='opacity .5s,transform .5s';
    fm.style.opacity='0'; fm.style.transform='translateY(-6px)';
    setTimeout(function(){ if(fm.parentNode) fm.parentNode.removeChild(fm); }, 520);
  }, 6000);
});

// Show more offers
(function(){
  var btn = document.getElementById('toggleMoreOffers'); if (!btn) return;
  var items = document.querySelectorAll('.oi-hidden'), open = false;
  btn.addEventListener('click', function(){
    open = !open;
    items.forEach(function(el){ el.style.display = open ? 'flex' : 'none'; });
    btn.innerHTML = open
      ? '<i class="fas fa-chevron-up" style="margin-right:4px"></i>Show less'
      : '<i class="fas fa-chevron-down" style="margin-right:4px"></i>Show '+items.length+' more';
  });
})();

function toggleAllUsers(source) {
  document.querySelectorAll('#usersTable tbody tr').forEach(function(r){
    if (r.style.display === 'none') return;
    var cb = r.querySelector('.rowCheck');
    if (cb) cb.checked = source.checked;
  });
}

// Table filter (now includes manager column)
function filterTable() {
  var nq = (document.getElementById('fName').value    || '').toLowerCase().trim();
  var iq = (document.getElementById('fId').value      || '').toLowerCase().trim();
  var dq = (document.getElementById('fDesig').value   || '').toLowerCase().trim();
  var lq = (document.getElementById('fLetter').value  || '').toLowerCase().trim();
  var mq = (document.getElementById('fManager').value || '').toLowerCase().trim();
  var rows = document.querySelectorAll('#usersTable tbody tr'), vis = 0;
  rows.forEach(function(r){
    if (!r.dataset.name) return;
    var show = true;
    if (nq && r.dataset.name.indexOf(nq)    === -1) show = false;
    if (iq && r.dataset.id.indexOf(iq)      === -1) show = false;
    if (dq && r.dataset.desig.indexOf(dq)   === -1) show = false;
    if (lq && r.dataset.letter !== lq)               show = false;
    if (mq && r.dataset.manager.indexOf(mq) === -1) show = false;
    r.style.display = show ? '' : 'none'; if (show) vis++;
  });
  var tf = document.getElementById('tableFooter');
  if (tf) tf.textContent = 'Showing ' + vis + ' of <?php echo count($users); ?> employees';
  var cb = document.getElementById('activeCount');
  if (cb) cb.textContent = vis + ' employees';
}
function clearFilters() {
  ['fName','fId','fManager'].forEach(function(id){ document.getElementById(id).value = ''; });
  ['fDesig','fLetter'].forEach(function(id){ document.getElementById(id).value = ''; });
  filterTable();
}

// ── REPORTING MANAGER MODAL ──────────────────────────────────────────────
function openManagerModal(empId, empName, currentManagerId) {
  document.getElementById('mmEmpId').value   = empId;
  document.getElementById('mmEmpName').textContent = empName;
  document.getElementById('mmSearch').value  = '';

  var sel = document.getElementById('mmManagerId');
  // Show all options first
  Array.from(sel.options).forEach(function(opt){ opt.style.display = ''; });
  // Pre-select current manager
  sel.value = currentManagerId || '';

  document.getElementById('managerModal').classList.add('open');
  setTimeout(function(){ document.getElementById('mmSearch').focus(); }, 150);
}
function closeManagerModal() {
  document.getElementById('managerModal').classList.remove('open');
}
function closeManagerModalOutside(e) {
  if (e.target === document.getElementById('managerModal')) closeManagerModal();
}
function filterManagerOptions() {
  var q   = document.getElementById('mmSearch').value.toLowerCase().trim();
  var sel = document.getElementById('mmManagerId');
  Array.from(sel.options).forEach(function(opt){
    if (opt.value === '') { opt.style.display = ''; return; } // always show "no manager"
    opt.style.display = (!q || opt.dataset.name.indexOf(q) !== -1) ? '' : 'none';
  });
}
// Close modal on Escape
document.addEventListener('keydown', function(e){
  if (e.key === 'Escape') closeManagerModal();
});
</script>
</body>
</html>
<?php $conn->close(); ?>