<?php
declare(strict_types=1);
ini_set('display_errors', '0');

require_once __DIR__ . '/../includes/console_shell.php';
require_login();

$pageLink = 'attendance/hrs-to-day-convert-policy.php';
$acl = require_acl('can_view', $pageLink);
$errors = [];
$flash = $_SESSION['flash_hrs_to_day_convert_policy'] ?? null;
unset($_SESSION['flash_hrs_to_day_convert_policy']);

function htd_stmt(mysqli $con, string $sql): mysqli_stmt
{
    $stmt = $con->prepare($sql);
    if (!$stmt) throw new RuntimeException('Unable to prepare hours-to-day policy query.');
    return $stmt;
}

function htd_options(mysqli $con, string $sql): array
{
    $rows = [];
    $result = $con->query($sql);
    if ($result) {
        while ($row = $result->fetch_assoc()) $rows[] = $row;
        $result->free();
    }
    return $rows;
}

function htd_valid_id(mysqli $con, string $table, int $id): bool
{
    $allowed = ['jos_app_mmonth', 'jos_app_year'];
    if ($id <= 0 || !in_array($table, $allowed, true)) return false;
    $stmt = htd_stmt($con, 'SELECT id FROM `' . $table . '` WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $valid = (bool)$stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $valid;
}

function htd_policy_exists(mysqli $con, int $id): bool
{
    $stmt = htd_stmt($con, 'SELECT id FROM jos_app_dayshrsconfig WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $exists = (bool)$stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $exists;
}

function htd_minutes($value, string $label, array &$errors): int
{
    $raw = trim((string)$value);
    if ($raw === '') {
        $errors[] = $label . ' is required when the component is selected.';
        return 0;
    }
    if (!preg_match('/^\d+$/', $raw)) {
        $errors[] = $label . ' must be whole minutes.';
        return 0;
    }
    $minutes = (int)$raw;
    if ($minutes < 0 || $minutes > 1440) {
        $errors[] = $label . ' must be between 0 and 1440 minutes.';
    }
    return $minutes;
}

function htd_grid_rows(mysqli $con, int $policyId): array
{
    $rows = [];
    $stmt = htd_stmt($con, 'SELECT g.id,g.configid,g.month,g.year,g.component,g.value,sc.componentname FROM jos_app_dayshrsconfig_grid g LEFT JOIN jos_app_salarycomponentmaster sc ON sc.id=g.component WHERE g.configid=? ORDER BY sc.orderby ASC,g.id ASC');
    $stmt->bind_param('i', $policyId);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) $rows[] = $row;
    $stmt->close();
    return $rows;
}

$months = htd_options($con, 'SELECT id,month AS name FROM jos_app_mmonth ORDER BY id');
$years = htd_options($con, 'SELECT id,year AS name,assessment FROM jos_app_year ORDER BY id DESC');
$components = htd_options($con, "SELECT id,componentname,orderby FROM jos_app_salarycomponentmaster WHERE dayshrsconfig='1' ORDER BY orderby ASC,id ASC");
$monthMap = $yearMap = $componentMap = [];
foreach ($months as $row) $monthMap[(int)$row['id']] = (string)$row['name'];
foreach ($years as $row) $yearMap[(int)$row['id']] = (string)$row['name'];
foreach ($components as $row) $componentMap[(int)$row['id']] = (string)$row['componentname'];

$mode = (string)($_GET['mode'] ?? '');
$editId = max(0, (int)($_GET['edit'] ?? 0));
$isForm = $mode === 'add' || $editId > 0;
$editRow = null;
$selectedValues = [];

if ($editId > 0) {
    $stmt = htd_stmt($con, 'SELECT * FROM jos_app_dayshrsconfig WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $editId);
    $stmt->execute();
    $editRow = $stmt->get_result()->fetch_assoc() ?: null;
    $stmt->close();
    if (!$editRow) {
        $_SESSION['flash_hrs_to_day_convert_policy'] = 'Hrs To Day Convert Policy was not found.';
        redirect('/attendance/hrs-to-day-convert-policy.php');
    }
    foreach (htd_grid_rows($con, $editId) as $gridRow) {
        $selectedValues[(int)$gridRow['component']] = (string)$gridRow['value'];
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['action'] ?? '');
    if (!verify_csrf($_POST['_csrf'] ?? null)) {
        $errors[] = 'Security token expired. Please refresh and try again.';
    } elseif ($action === 'save') {
        $id = max(0, (int)($_POST['id'] ?? 0));
        if ($id > 0 && empty($acl['can_edit'])) $errors[] = 'You do not have permission to edit Hrs To Day Convert policies.';
        if ($id === 0 && empty($acl['can_add'])) $errors[] = 'You do not have permission to add Hrs To Day Convert policies.';
        if ($id > 0 && !htd_policy_exists($con, $id)) $errors[] = 'Hrs To Day Convert Policy was not found.';

        $name = trim((string)($_POST['name'] ?? ''));
        $month = max(0, (int)($_POST['month'] ?? 0));
        $year = max(0, (int)($_POST['year'] ?? 0));
        $checked = array_map('intval', (array)($_POST['component_selected'] ?? []));
        $checked = array_values(array_unique(array_filter($checked, static fn($value) => $value > 0)));
        $values = (array)($_POST['value'] ?? []);
        $rowsToSave = [];

        if ($name === '') $errors[] = 'Policy name is required.';
        if (mb_strlen($name) > 150) $errors[] = 'Policy name must be 150 characters or fewer.';
        if (!htd_valid_id($con, 'jos_app_mmonth', $month)) $errors[] = 'Select a valid month.';
        if (!htd_valid_id($con, 'jos_app_year', $year)) $errors[] = 'Select a valid year.';
        if (!$components) $errors[] = 'No salary components are enabled for Hrs To Day conversion.';

        $validComponentIds = array_map(static fn($row) => (int)$row['id'], $components);
        foreach ($checked as $componentId) {
            if (!in_array($componentId, $validComponentIds, true)) {
                $errors[] = 'Invalid salary component selected.';
                break;
            }
        }

        foreach ($components as $component) {
            $componentId = (int)$component['id'];
            if (!in_array($componentId, $checked, true)) continue;
            $minutes = htd_minutes($values[$componentId] ?? '', (string)$component['componentname'], $errors);
            $rowsToSave[] = ['component' => $componentId, 'value' => $minutes];
        }
        if (!$rowsToSave) $errors[] = 'Select at least one salary component and enter its one-day minutes.';

        if (!$errors) {
            $con->begin_transaction();
            try {
                if ($id > 0) {
                    $stmt = htd_stmt($con, 'UPDATE jos_app_dayshrsconfig SET name=?,month=?,year=? WHERE id=?');
                    $stmt->bind_param('siii', $name, $month, $year, $id);
                    if (!$stmt->execute()) throw new RuntimeException('Unable to update Hrs To Day Convert Policy.');
                    $stmt->close();
                    $savedId = $id;
                } else {
                    $stmt = htd_stmt($con, 'INSERT INTO jos_app_dayshrsconfig (name,month,year) VALUES (?,?,?)');
                    $stmt->bind_param('sii', $name, $month, $year);
                    if (!$stmt->execute()) throw new RuntimeException('Unable to add Hrs To Day Convert Policy.');
                    $savedId = (int)$con->insert_id;
                    $stmt->close();
                }

                $stmt = htd_stmt($con, 'DELETE FROM jos_app_dayshrsconfig_grid WHERE configid=?');
                $stmt->bind_param('i', $savedId);
                $stmt->execute();
                $stmt->close();

                foreach ($rowsToSave as $row) {
                    $stmt = htd_stmt($con, 'INSERT INTO jos_app_dayshrsconfig_grid (configid,month,year,component,value) VALUES (?,?,?,?,?)');
                    $stmt->bind_param('iiiii', $savedId, $month, $year, $row['component'], $row['value']);
                    if (!$stmt->execute()) throw new RuntimeException('Unable to save Hrs To Day Convert component row.');
                    $stmt->close();
                }

                $con->commit();
                audit_log($id > 0 ? 'hrs_to_day_convert_policy.update' : 'hrs_to_day_convert_policy.create', 'jos_app_dayshrsconfig', (string)$savedId, $name);
                $_SESSION['flash_hrs_to_day_convert_policy'] = $id > 0 ? 'Hrs To Day Convert Policy updated successfully.' : 'Hrs To Day Convert Policy added successfully.';
                redirect('/attendance/hrs-to-day-convert-policy.php');
            } catch (Throwable $e) {
                $con->rollback();
                $errors[] = 'Unable to save the Hrs To Day Convert Policy. No changes were committed.';
            }
        }

        $isForm = true;
        $editId = $id;
        $editRow = ['id' => $id, 'name' => $name, 'month' => $month, 'year' => $year];
        $selectedValues = [];
        foreach ($rowsToSave as $row) $selectedValues[(int)$row['component']] = (string)$row['value'];
    }
}

$filterMonth = max(0, (int)($_GET['month'] ?? 0));
$filterYear = max(0, (int)($_GET['year'] ?? 0));
$search = trim((string)($_GET['q'] ?? ''));
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 20;
$totalRows = 0;
$rows = [];
$pages = 1;

if (!$isForm) {
    $where = ['1=1'];
    $types = '';
    $params = [];
    if ($filterMonth > 0) { $where[] = 'p.month=?'; $types .= 'i'; $params[] = $filterMonth; }
    if ($filterYear > 0) { $where[] = 'p.year=?'; $types .= 'i'; $params[] = $filterYear; }
    if ($search !== '') { $where[] = 'p.name LIKE ?'; $types .= 's'; $params[] = '%' . $search . '%'; }
    $whereSql = implode(' AND ', $where);

    $stmt = htd_stmt($con, 'SELECT COUNT(*) AS total FROM jos_app_dayshrsconfig p WHERE ' . $whereSql);
    if ($types !== '') $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $totalRows = (int)($stmt->get_result()->fetch_assoc()['total'] ?? 0);
    $stmt->close();
    $pages = max(1, (int)ceil($totalRows / $perPage));
    $page = min($page, $pages);
    $offset = ($page - 1) * $perPage;

    $stmt = htd_stmt($con, 'SELECT p.*,m.month AS month_name,y.year AS year_name,COUNT(g.id) AS component_count FROM jos_app_dayshrsconfig p LEFT JOIN jos_app_mmonth m ON m.id=p.month LEFT JOIN jos_app_year y ON y.id=p.year LEFT JOIN jos_app_dayshrsconfig_grid g ON g.configid=p.id WHERE ' . $whereSql . ' GROUP BY p.id,m.month,y.year ORDER BY y.year DESC,p.year DESC,p.month DESC,p.id DESC LIMIT ? OFFSET ?');
    $listTypes = $types . 'ii';
    $listParams = $params;
    $listParams[] = $perPage;
    $listParams[] = $offset;
    $stmt->bind_param($listTypes, ...$listParams);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $row['grid'] = htd_grid_rows($con, (int)$row['id']);
        $rows[] = $row;
    }
    $stmt->close();
}

$value = static function (string $key, $default = '') use (&$editRow) { return $editRow[$key] ?? $default; };
$input = 'mt-1 w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm text-slate-800 outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-100';
$selectSmall = 'rounded-xl border border-slate-200 px-3 py-2.5 text-sm';

console_header('Hrs To Day Convert Policy', $pageLink);
?>
<div class="mb-4 flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
  <div><div class="mb-2 flex items-center gap-2 text-xs font-semibold text-slate-500"><a href="/dashboard.php">Dashboard</a><i class="fa-solid fa-chevron-right text-[9px]"></i><span>D. Masters</span><i class="fa-solid fa-chevron-right text-[9px]"></i><span>Attendance Settings</span><i class="fa-solid fa-chevron-right text-[9px]"></i><span class="text-brand-600">Hrs To Day Convert Policy</span></div><h1 class="text-2xl font-bold text-slate-900">Hrs To Day Convert Policy</h1><p class="mt-1 text-sm text-slate-500">Configure one-day minutes for salary components that convert attendance hours to days.</p></div>
</div>
<?php if ($flash): ?><div class="mb-5 rounded-xl border border-emerald-100 bg-emerald-50 px-5 py-4 text-sm font-semibold text-emerald-700"><i class="fa-solid fa-circle-check mr-2"></i><?= h($flash) ?></div><?php endif; ?>
<?php if ($errors): ?><div class="mb-5 rounded-xl border border-red-100 bg-red-50 px-5 py-4 text-sm font-semibold text-red-700"><div class="font-bold">Please fix the following</div><ul class="mt-2 list-inside list-disc"><?php foreach($errors as $error): ?><li><?= h($error) ?></li><?php endforeach; ?></ul></div><?php endif; ?>

<?php if ($isForm): ?>
<form method="post" id="hrs-to-day-policy-form" class="space-y-4">
  <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>"><input type="hidden" name="action" value="save"><input type="hidden" name="id" value="<?= (int)$value('id', 0) ?>">
  <section class="rounded-2xl border border-slate-100 bg-white p-4 shadow-sm">
    <div class="mb-4 flex flex-wrap items-center justify-between gap-3"><div class="flex items-center gap-3"><span class="flex h-9 w-9 items-center justify-center rounded-lg bg-brand-50 text-brand-600"><i class="fa-solid fa-clock"></i></span><div><h2 class="font-bold text-slate-800"><?= (int)$value('id',0)>0?'Edit Hrs To Day Convert Policy':'New Hrs To Day Convert Policy' ?></h2><p class="text-xs text-slate-400">Fields marked with * are required.</p></div></div><a href="/attendance/hrs-to-day-convert-policy.php" class="rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm font-bold text-slate-600 hover:bg-slate-50"><i class="fa-solid fa-arrow-left mr-2"></i>Back to List</a></div>
    <div class="grid gap-3 md:grid-cols-3">
      <label class="text-sm font-semibold text-slate-700">Policy Name *<input name="name" required maxlength="150" value="<?= h((string)$value('name')) ?>" class="<?= $input ?>" placeholder="Policy Name"></label>
      <label class="text-sm font-semibold text-slate-700">Month *<select name="month" required class="<?= $input ?>"><option value="">Select Month</option><?php foreach($months as $option): ?><option value="<?= (int)$option['id'] ?>" <?= (int)$value('month')===(int)$option['id']?'selected':'' ?>><?= h($option['name']) ?></option><?php endforeach; ?></select></label>
      <label class="text-sm font-semibold text-slate-700">Year *<select name="year" required class="<?= $input ?>"><option value="">Select Year</option><?php foreach($years as $option): ?><option value="<?= (int)$option['id'] ?>" <?= (int)$value('year')===(int)$option['id']?'selected':'' ?>><?= h($option['name']) ?><?= $option['assessment']?' · '.h($option['assessment']):'' ?></option><?php endforeach; ?></select></label>
    </div>
  </section>
  <section class="overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm">
    <div class="border-b border-slate-100 px-5 py-4"><h2 class="font-bold text-slate-800">Component Conversion Rules</h2><p class="mt-1 text-xs font-medium text-slate-400">Select salary components and enter one-day value in minutes.</p></div>
    <div class="overflow-x-auto"><table class="w-full min-w-[720px] text-left text-sm"><thead class="bg-slate-50 text-[10px] uppercase tracking-wider text-slate-400"><tr><th class="px-5 py-4 w-20">Use</th><th class="px-5 py-4 w-20">Sr No</th><th class="px-5 py-4">Component Name</th><th class="px-5 py-4 w-64">One Day Hrs (MM)</th></tr></thead><tbody class="divide-y divide-slate-100">
    <?php if(!$components): ?><tr><td colspan="4" class="px-6 py-10 text-center font-semibold text-slate-400">No salary components are enabled for Hrs To Day conversion.</td></tr><?php endif; ?>
    <?php foreach($components as $index=>$component): $componentId=(int)$component['id']; $checked=array_key_exists($componentId,$selectedValues); ?><tr><td class="px-5 py-4"><input type="checkbox" name="component_selected[]" value="<?= $componentId ?>" <?= $checked?'checked':'' ?> class="h-4 w-4 rounded border-slate-300 text-brand-600 focus:ring-brand-500"></td><td class="px-5 py-4 font-semibold text-slate-500"><?= $index + 1 ?></td><td class="px-5 py-4"><div class="font-bold text-slate-800"><?= h((string)$component['componentname']) ?></div><div class="text-xs text-slate-400">Component #<?= $componentId ?></div></td><td class="px-5 py-4"><input name="value[<?= $componentId ?>]" inputmode="numeric" pattern="\d*" value="<?= h($selectedValues[$componentId] ?? '') ?>" class="<?= $input ?> mt-0" placeholder="Minutes"></td></tr><?php endforeach; ?>
    </tbody></table></div>
  </section>
  <div class="flex flex-wrap justify-end gap-2"><a href="/attendance/hrs-to-day-convert-policy.php" class="rounded-lg border border-slate-200 bg-white px-5 py-2.5 text-sm font-bold text-slate-600">Cancel</a><button class="rounded-lg bg-brand-600 px-5 py-2.5 text-sm font-bold text-white hover:bg-brand-700"><i class="fa-solid fa-floppy-disk mr-2"></i>Save Policy</button></div>
</form>
<?php else: ?>
<section class="overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm">
  <div class="flex flex-col gap-3 border-b border-slate-100 px-5 py-4 sm:flex-row sm:items-center sm:justify-between"><div><h2 class="font-bold text-slate-800">Hrs To Day Convert Policy List</h2><p class="mt-1 text-xs font-medium text-slate-400">Policies are ordered by latest year and month.</p></div><?php if(!empty($acl['can_add'])): ?><a href="?mode=add" class="inline-flex items-center justify-center gap-2 rounded-lg bg-brand-600 px-4 py-2.5 text-sm font-bold text-white shadow-sm hover:bg-brand-700"><i class="fa-solid fa-plus"></i>+ Add</a><?php endif; ?></div>
  <form method="get" class="grid gap-3 border-b border-slate-100 p-5 md:grid-cols-2 xl:grid-cols-5"><input type="search" name="q" value="<?= h($search) ?>" placeholder="Search policy name" class="<?= $selectSmall ?>"><select name="month" class="<?= $selectSmall ?>"><option value="0">All Months</option><?php foreach($months as $option): ?><option value="<?= (int)$option['id'] ?>" <?= $filterMonth===(int)$option['id']?'selected':'' ?>><?= h($option['name']) ?></option><?php endforeach; ?></select><select name="year" class="<?= $selectSmall ?>"><option value="0">All Years</option><?php foreach($years as $option): ?><option value="<?= (int)$option['id'] ?>" <?= $filterYear===(int)$option['id']?'selected':'' ?>><?= h($option['name']) ?></option><?php endforeach; ?></select><div class="flex gap-2 xl:col-span-2"><button class="rounded-xl bg-slate-900 px-5 py-2.5 text-sm font-bold text-white"><i class="fa-solid fa-filter mr-2"></i>Filter</button><a href="/attendance/hrs-to-day-convert-policy.php" class="rounded-xl border border-slate-200 px-5 py-2.5 text-sm font-bold text-slate-600">Clear</a></div></form>
  <div class="overflow-x-auto"><table class="w-full min-w-[1040px] text-left text-sm"><thead class="bg-slate-50 text-[10px] uppercase tracking-wider text-slate-400"><tr><th class="px-5 py-4 w-20">Sr No</th><th class="px-5 py-4">Policy Name</th><th class="px-5 py-4">Month</th><th class="px-5 py-4">Year</th><th class="px-5 py-4">Conversion Rules</th><th class="px-5 py-4 text-right">Actions</th></tr></thead><tbody class="divide-y divide-slate-100">
    <?php if(!$rows): ?><tr><td colspan="6" class="px-6 py-14 text-center font-semibold text-slate-400">No Hrs To Day Convert policies found.</td></tr><?php endif; ?>
    <?php foreach($rows as $index=>$row): ?><tr class="align-top hover:bg-slate-50/70"><td class="px-5 py-4 font-semibold text-slate-500"><?= (($page-1)*$perPage)+$index+1 ?></td><td class="px-5 py-4"><div class="font-bold text-slate-800"><?= h($row['name']) ?></div><div class="text-xs text-slate-400">Policy #<?= (int)$row['id'] ?></div></td><td class="px-5 py-4 font-semibold text-slate-700"><?= h($row['month_name'] ?: ($monthMap[(int)$row['month']] ?? 'Unknown')) ?></td><td class="px-5 py-4 font-semibold text-slate-700"><?= h($row['year_name'] ?: ($yearMap[(int)$row['year']] ?? (string)$row['year'])) ?></td><td class="px-5 py-4"><div class="overflow-hidden rounded-xl border border-slate-100"><table class="w-full text-xs"><thead class="bg-slate-50 text-[10px] uppercase text-slate-400"><tr><th class="px-3 py-2 text-left">Component</th><th class="px-3 py-2 text-left">Minutes</th></tr></thead><tbody><?php if(empty($row['grid'])): ?><tr><td colspan="2" class="px-3 py-3 text-center font-semibold text-slate-400">No selected components</td></tr><?php endif; ?><?php foreach($row['grid'] as $grid): ?><tr class="border-t border-slate-100"><td class="px-3 py-2 font-semibold"><?= h((string)($grid['componentname'] ?: ($componentMap[(int)$grid['component']] ?? 'Component #' . (int)$grid['component']))) ?></td><td class="px-3 py-2 font-semibold"><?= h((string)$grid['value']) ?></td></tr><?php endforeach; ?></tbody></table></div></td><td class="px-5 py-4"><div class="flex justify-end gap-2"><?php if(!empty($acl['can_edit'])): ?><a href="?edit=<?= (int)$row['id'] ?>" class="rounded-lg border border-slate-200 px-3 py-2 text-slate-600 hover:bg-brand-50 hover:text-brand-600" title="Edit"><i class="fa-solid fa-pen"></i></a><?php endif; ?></div></td></tr><?php endforeach; ?>
  </tbody></table></div>
  <?php if($totalRows>$perPage): ?><div class="flex items-center justify-between border-t border-slate-100 px-5 py-4 text-sm"><span class="font-medium text-slate-500"><?= $totalRows ?> policies</span><div class="flex gap-2"><?php $base=['q'=>$search,'month'=>$filterMonth,'year'=>$filterYear]; if($page>1): ?><a class="rounded-lg border border-slate-200 px-4 py-2 font-semibold" href="?<?= h(http_build_query($base + ['page'=>$page-1])) ?>">Previous</a><?php endif; ?><?php if($page<$pages): ?><a class="rounded-lg border border-slate-200 px-4 py-2 font-semibold" href="?<?= h(http_build_query($base + ['page'=>$page+1])) ?>">Next</a><?php endif; ?></div></div><?php endif; ?>
</section>
<?php endif; ?>
<?php console_footer(); ?>
