<?php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/db.php';
require_login();

$mysqli = db();
$id = (int)($_GET['id'] ?? 0);
if (!$id) { echo 'Missing id'; exit; }

// Load payroll row
$stmt = $mysqli->prepare('SELECT p.*, e.full_name, e.emp_code FROM salary_payroll p LEFT JOIN employees e ON e.id=p.employee_id WHERE p.id=?');
$stmt->bind_param('i',$id); $stmt->execute(); $pay = $stmt->get_result()->fetch_assoc();
if (!$pay) { echo 'Not found'; exit; }

// Load period bounds for breakdown
$month = (int)$pay['period_month']; $year = (int)$pay['period_year'];
$first = sprintf('%04d-%02d-01',$year,$month);
$last = date('Y-m-t', strtotime($first));

// Sums used (already stored but also show detailed lists if desired later)
$gross = (float)$pay['gross_salary'];
$adv = (float)$pay['total_advances'];
$ded = (float)$pay['total_deductions'];
$net = (float)$pay['net_salary'];

// Allowances for the period (informational; net/gross may already account for these in payroll calc)
$allowances = [];
$allow_total = 0.0;
if (!empty($pay['employee_id'])) {
  $eid = (int)$pay['employee_id'];
  $resAll = $mysqli->query("SELECT id, all_date, amount, reason FROM salary_allowances WHERE employee_id=".$eid." AND all_date BETWEEN '".$mysqli->real_escape_string($first)."' AND '".$mysqli->real_escape_string($last)."' ORDER BY all_date ASC, id ASC");
  if ($resAll) {
    while($r=$resAll->fetch_assoc()){ $allowances[]=$r; $allow_total += (float)$r['amount']; }
  }
}

// Incentives for the period
$incentives = [];
$inc_total = 0.0;
if (!empty($pay['employee_id'])) {
  $eid = (int)$pay['employee_id'];
  $resInc = $mysqli->query("SELECT id, inc_date, amount, reason FROM salary_incentives WHERE employee_id=".$eid." AND inc_date BETWEEN '".$mysqli->real_escape_string($first)."' AND '".$mysqli->real_escape_string($last)."' ORDER BY inc_date ASC, id ASC");
  if ($resInc) {
    while($r=$resInc->fetch_assoc()){ $incentives[]=$r; $inc_total += (float)$r['amount']; }
  }
}

// Shop settings
$settings = [ 'company_name'=>'Granite Warehouse','address_line'=>'Warehouse Address Line','city_country'=>'City, Country','company_email'=>'','phone'=>'-' ];
$resSet = $mysqli->query('SELECT company_name, address_line, city_country, company_email, phone FROM shop_settings ORDER BY id ASC LIMIT 1');
if ($resSet && $rowS = $resSet->fetch_assoc()) { $settings = array_merge($settings, $rowS); }
// Try to get logo URL if column exists
$logo_url = null;
$chk = $mysqli->query("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='".$mysqli->real_escape_string(DB_NAME)."' AND TABLE_NAME='shop_settings' AND COLUMN_NAME='logo_url' LIMIT 1");
if ($chk && $chk->fetch_row()) {
  $resLogo = $mysqli->query('SELECT logo_url FROM shop_settings ORDER BY id ASC LIMIT 1');
  if ($resLogo && ($rowL=$resLogo->fetch_assoc())) { $logo_url = $rowL['logo_url'] ?? null; }
}
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Salary Slip - <?php echo htmlspecialchars($pay['full_name']); ?> (<?php echo date('M Y', strtotime($first)); ?>)</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body { 
      background:#fff; 
      font-size: 13px; 
      line-height: 1.2;
    }
    .slip { 
      max-width: 800px; 
      margin: 5px auto; 
      border:1px solid #dee2e6; 
      padding:8px;
    }
    .header { 
      border-bottom:1px solid #dee2e6; 
      padding-bottom:5px; 
      margin-bottom:8px; 
    }
    .company { 
      font-weight:600; 
      font-size:14px; 
    }
    .meta label { 
      width: 120px; 
      display:inline-block; 
      color:#6c757d; 
      margin-bottom: 2px;
    }
    .table-sm th, 
    .table-sm td { 
      padding: 0.15rem 0.4rem; 
      font-size: 12px;
    }
    h6 {
      font-size: 13px;
      margin-bottom: 5px;
    }
    @media print { 
      .no-print { 
        display:none !important; 
      }
      body {
        font-size: 12px;
      }
    }
  </style>
</head>
<body>
  <div class="slip">
    <div class="d-flex justify-content-between align-items-start header">
      <div>
        <?php if (!empty($logo_url)): ?>
          <div class="mb-1"><img src="<?php echo htmlspecialchars($logo_url); ?>" alt="Logo" style="height:60px;"></div>
        <?php else: ?>
          <div class="company"><?php echo htmlspecialchars($settings['company_name']); ?></div>
        <?php endif; ?>
        <div><?php echo htmlspecialchars($settings['address_line']); ?></div>
        <div><?php echo htmlspecialchars($settings['city_country']); ?></div>
        <div>Email: <?php echo htmlspecialchars($settings['company_email']); ?> | Phone: <?php echo htmlspecialchars($settings['phone']); ?></div>
      </div>
      <div class="text-end">
        <button class="btn btn-primary no-print" onclick="window.print()">Print</button>
      </div>
    </div>

    <div class="row mb-3">
      <div class="col-md-7 meta">
        <div><label>Employee:</label> <strong><?php echo htmlspecialchars($pay['full_name']); ?></strong> (<?php echo htmlspecialchars($pay['emp_code'] ?? ''); ?>)</div>
        <div><label>Period:</label> <?php echo date('F Y', strtotime($first)); ?></div>
        <div><label>Generated On:</label> <?php echo htmlspecialchars(date('Y-m-d', strtotime($pay['generated_on'] ?? date('Y-m-d')))); ?></div>
      </div>
      <div class="col-md-5">
        <table class="table table-sm">
          <tbody>
            <tr><th>Gross Salary</th><td class="text-end"><?php echo number_format($gross,2); ?></td></tr>
            <tr><th>Total Allowances</th><td class="text-end"><?php echo number_format($allow_total,2); ?></td></tr>
            <tr><th>Total OT</th><td class="text-end"><?php echo number_format($inc_total,2); ?></td></tr>
            <tr><th>Total Advances</th><td class="text-end"><?php echo number_format($adv,2); ?></td></tr>
            <tr><th>Total Deductions</th><td class="text-end"><?php echo number_format($ded,2); ?></td></tr>
            <tr class="table-light"><th>Net Salary</th><td class="text-end"><strong><?php echo number_format($net,2); ?></strong></td></tr>
          </tbody>
        </table>
      </div>
    </div>

    <?php if ($allowances): ?>
    <div class="mb-3">
      <h6>Allowances (<?php echo date('Y-m-d', strtotime($first)); ?> to <?php echo date('Y-m-d', strtotime($last)); ?>)</h6>
      <div class="table-responsive">
        <table class="table table-sm align-middle">
          <thead><tr><th style="width:120px;">Date</th><th>Reason</th><th class="text-end" style="width:160px;">Amount</th></tr></thead>
          <tbody>
            <?php foreach ($allowances as $a): ?>
            <tr>
              <td><?php echo htmlspecialchars($a['all_date']); ?></td>
              <td><?php echo htmlspecialchars($a['reason'] ?? ''); ?></td>
              <td class="text-end"><?php echo number_format((float)$a['amount'],2); ?></td>
            </tr>
            <?php endforeach; ?>
            <tr class="table-light">
              <th colspan="2" class="text-end">Total</th>
              <th class="text-end"><?php echo number_format($allow_total,2); ?></th>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <?php endif; ?>

    <?php if ($incentives): ?>
    <div class="mb-3">
      <h6>OT (<?php echo date('Y-m-d', strtotime($first)); ?> to <?php echo date('Y-m-d', strtotime($last)); ?>)</h6>
      <div class="table-responsive">
        <table class="table table-sm align-middle">
          <thead><tr><th style="width:120px;">Date</th><th>Reason</th><th class="text-end" style="width:160px;">Amount</th></tr></thead>
          <tbody>
            <?php foreach ($incentives as $a): ?>
            <tr>
              <td><?php echo htmlspecialchars($a['inc_date']); ?></td>
              <td><?php echo htmlspecialchars($a['reason'] ?? ''); ?></td>
              <td class="text-end"><?php echo number_format((float)$a['amount'],2); ?></td>
            </tr>
            <?php endforeach; ?>
            <tr class="table-light">
              <th colspan="2" class="text-end">Total</th>
              <th class="text-end"><?php echo number_format($inc_total,2); ?></th>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <?php endif; ?>

    <?php if (!empty($pay['employee_id'])): 
    // Fetch attendance summary for the month
    $attStmt = $mysqli->prepare('
        SELECT 
            COUNT(DISTINCT DATE(att_date)) as total_days,
            SUM(CASE WHEN status = "present" THEN 1 ELSE 0 END) as present_days,
            SUM(CASE WHEN status = "half_day" THEN 1 ELSE 0 END) as half_days,
            SUM(CASE WHEN status = "short_leave" THEN 1 ELSE 0 END) as shortleave_days,
            SEC_TO_TIME(SUM(TIMESTAMPDIFF(SECOND, check_in, COALESCE(check_out, check_in)))) as total_time,
            SUM(hours_worked)  as total_hours,
            SUM(ot_minutes) /60 as total_ot
        FROM employees_attendance 
        WHERE employee_id = ? 
        AND DATE(att_date) BETWEEN ? AND ?
    ');
    $attStmt->bind_param('iss', $pay['employee_id'], $first, $last);
    $attStmt->execute();
    $attResult = $attStmt->get_result();
    $attSummary = $attResult->fetch_assoc();


    
    // Calculate additional metrics
    $total_days = (int)($attSummary['total_days'] ?? 0);
    $present_days = (int)($attSummary['present_days'] ?? 0);
    $half_days = (int)($attSummary['half_days'] ?? 0);
    $shortleave_days = (int)($attSummary['shortleave_days'] ?? 0);
    $absent_days = $total_days - $present_days;
    $total_hours = (float)($attSummary['total_hours'] ?? 0);
    $total_ot = (float)($attSummary['total_ot'] ?? 0);
    
    ?>
    <div class="mb-3">
        <h6>Attendance Summary (<?php echo date('M Y', strtotime($first)); ?>)</h6>
        <div class="table-responsive">
            <table class="table table-sm align-middle">
                <thead>
                    <tr>
                        <th>Working Days</th>
                        <th>Present</th>
                        <th>Leave</th>
                        <th>Half Day</th>
                        <th>Short Leave</th>
                        <th>Total Hours </th>
                        <th>OT Hours</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><?php echo $total_days; ?> days</td>
                        <td><?php echo $present_days; ?> days</td>
                        <td><?php echo $absent_days; ?> days</td>
                        <td><?php echo $half_days; ?> days</td>
                        <td><?php echo $shortleave_days; ?> days</td>
                        <td><?php echo number_format($total_hours, 2); ?> </td>
                        <td><?php echo number_format($total_ot, 2); ?> </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>

    <div class="row mt-4">
      <div class="col-6 text-center" style="padding-top:40px; border-top:1px solid #dee2e6; margin-top:40px;">Employee Signature</div>
      <div class="col-6 text-center" style="padding-top:40px; border-top:1px solid #dee2e6; margin-top:40px;">Authorized Signature</div>
    </div>
  </div>
</body>
</html>
