<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
startSession(); requireLogin();
$db = Database::getInstance();
$page = 'My Profile';
$user = currentUser();
$empId = $user['emp_id'];

if (!$empId) { echo "<div class='alert alert-warning m-3'>No employee record linked to your account.</div>"; include __DIR__ . '/../../includes/footer.php'; exit; }

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $db->execute("UPDATE employees SET personal_email=?,mobile=?,alternate_phone=?,blood_group=?,marital_status=?,emergency_name=?,emergency_relation=?,emergency_phone=?,residential_address=?,residential_city=?,residential_state=?,residential_pincode=? WHERE id=?",
        [post('personal_email'),post('mobile'),post('alternate_phone'),post('blood_group'),post('marital_status'),post('emergency_name'),post('emergency_relation'),post('emergency_phone'),post('residential_address'),post('residential_city'),post('residential_state'),post('residential_pincode'),$empId]);
    setFlash('success','Profile updated successfully.');
    header('Location: '.BASE_URL.'/modules/employees/profile.php'); exit;
}

$emp  = $db->fetchOne("SELECT e.*,d.name AS dept,des.name AS designation,g.name AS grade,l.name AS location,s.name AS shift,CONCAT(m.first_name,' ',m.last_name) AS manager FROM employees e LEFT JOIN departments d ON d.id=e.department_id LEFT JOIN designations des ON des.id=e.designation_id LEFT JOIN grades g ON g.id=e.grade_id LEFT JOIN locations l ON l.id=e.location_id LEFT JOIN shifts s ON s.id=e.shift_id LEFT JOIN employees m ON m.id=e.reporting_manager_id WHERE e.id=?", [$empId]);
$salary = $db->fetchOne("SELECT gross_monthly,ctc_annual FROM employee_salary WHERE employee_id=?", [$empId]);
$leaveBalance = $db->fetchAll("SELECT lb.*,lt.name AS leave_name,lt.code FROM employee_leave_balance lb JOIN leave_types lt ON lt.id=lb.leave_type_id WHERE lb.employee_id=? AND lb.year=YEAR(NOW())", [$empId]);

include __DIR__ . '/../../includes/header.php';
?>
<div class="row g-3">
  <!-- Profile card -->
  <div class="col-md-4">
    <div class="pc-card text-center mb-3">
      <div style="width:80px;height:80px;background:var(--pc-brand-light);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:28px;font-weight:800;color:var(--pc-brand);margin:0 auto 12px">
        <?=strtoupper(substr($emp['first_name'],0,1).substr($emp['last_name'],0,1))?>
      </div>
      <h6 class="fw-bold mb-0"><?=clean($emp['first_name'].' '.$emp['last_name'])?></h6>
      <div class="text-muted small mb-2"><?=clean($emp['designation']??'—')?></div>
      <div class="badge" style="background:var(--pc-brand-light);color:var(--pc-brand)"><?=clean($emp['employee_id'])?></div>
      <hr>
      <?php foreach([['Department',$emp['dept']??'—'],['Location',$emp['location']??'—'],['Shift',$emp['shift']??'—'],['Manager',$emp['manager']??'—'],['Joining',fmtDate($emp['date_of_joining'])],['Status',ucfirst($emp['status'])]] as [$k,$v]): ?>
      <div class="d-flex justify-content-between py-1" style="font-size:12px"><span class="text-muted"><?=$k?></span><span class="fw-semibold"><?=clean($v)?></span></div>
      <?php endforeach; ?>
    </div>
    <!-- Leave Balance -->
    <div class="pc-card">
      <div class="pc-card-title">Leave Balance <?=date('Y')?></div>
      <?php foreach($leaveBalance as $lb): ?>
      <div class="mb-2">
        <div class="d-flex justify-content-between small mb-1"><span><?=clean($lb['leave_name'])?></span><span class="fw-bold"><?=$lb['allocated']-$lb['used']?> / <?=$lb['allocated']?></span></div>
        <div class="pc-progress"><div class="pc-progress-fill" style="width:<?=$lb['allocated']>0?round((($lb['allocated']-$lb['used'])/$lb['allocated'])*100):0?>%"></div></div>
      </div>
      <?php endforeach; if(!$leaveBalance): ?><div class="text-muted small text-center">No leave balance found</div><?php endif; ?>
    </div>
  </div>

  <!-- Edit form -->
  <div class="col-md-8">
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-user-edit me-2"></i>Update Profile</div>
      <form method="POST">
        <?=csrfField()?>
        <div class="pc-section-divider">Personal Information</div>
        <div class="row g-3">
          <div class="col-md-6"><label class="pc-label">First Name</label><input type="text" class="form-control form-control-sm" value="<?=clean($emp['first_name'])?>" disabled></div>
          <div class="col-md-6"><label class="pc-label">Last Name</label><input type="text" class="form-control form-control-sm" value="<?=clean($emp['last_name'])?>" disabled></div>
          <div class="col-md-4"><label class="pc-label">Date of Birth</label><input type="date" class="form-control form-control-sm" value="<?=$emp['date_of_birth']?>" disabled></div>
          <div class="col-md-4"><label class="pc-label">Blood Group</label>
            <select name="blood_group" class="form-select form-select-sm"><option value="">Select</option><?php foreach(['A+','A-','B+','B-','AB+','AB-','O+','O-'] as $bg): ?><option value="<?=$bg?>" <?=$emp['blood_group']===$bg?'selected':''?>><?=$bg?></option><?php endforeach; ?></select></div>
          <div class="col-md-4"><label class="pc-label">Marital Status</label>
            <select name="marital_status" class="form-select form-select-sm"><option value="">Select</option><?php foreach(['single','married','divorced','widowed'] as $ms): ?><option value="<?=$ms?>" <?=$emp['marital_status']===$ms?'selected':''?>><?=ucfirst($ms)?></option><?php endforeach; ?></select></div>
        </div>
        <div class="pc-section-divider">Contact Details</div>
        <div class="row g-3">
          <div class="col-md-6"><label class="pc-label">Personal Email</label><input type="email" name="personal_email" class="form-control form-control-sm" value="<?=clean($emp['personal_email'])?>"></div>
          <div class="col-md-3"><label class="pc-label">Mobile</label><input type="text" name="mobile" class="form-control form-control-sm" value="<?=clean($emp['mobile'])?>"></div>
          <div class="col-md-3"><label class="pc-label">Alternate Phone</label><input type="text" name="alternate_phone" class="form-control form-control-sm" value="<?=clean($emp['alternate_phone'])?>"></div>
          <div class="col-12"><label class="pc-label">Residential Address</label><textarea name="residential_address" class="form-control form-control-sm" rows="2"><?=clean($emp['residential_address'])?></textarea></div>
          <div class="col-md-4"><label class="pc-label">City</label><input type="text" name="residential_city" class="form-control form-control-sm" value="<?=clean($emp['residential_city'])?>"></div>
          <div class="col-md-4"><label class="pc-label">State</label><input type="text" name="residential_state" class="form-control form-control-sm" value="<?=clean($emp['residential_state'])?>"></div>
          <div class="col-md-4"><label class="pc-label">Pincode</label><input type="text" name="residential_pincode" class="form-control form-control-sm" value="<?=clean($emp['residential_pincode'])?>"></div>
        </div>
        <div class="pc-section-divider">Emergency Contact</div>
        <div class="row g-3">
          <div class="col-md-4"><label class="pc-label">Name</label><input type="text" name="emergency_name" class="form-control form-control-sm" value="<?=clean($emp['emergency_name'])?>"></div>
          <div class="col-md-4"><label class="pc-label">Relation</label><input type="text" name="emergency_relation" class="form-control form-control-sm" value="<?=clean($emp['emergency_relation'])?>"></div>
          <div class="col-md-4"><label class="pc-label">Phone</label><input type="text" name="emergency_phone" class="form-control form-control-sm" value="<?=clean($emp['emergency_phone'])?>"></div>
        </div>
        <div class="mt-3"><button class="btn btn-pc"><i class="ti ti-device-floppy me-1"></i>Save Profile</button></div>
      </form>
    </div>
  </div>
</div>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
