<?php
require_once __DIR__ . '/config/config.php';
require_role(['admin']);

$roles = ['superadmin','admin','hr','audit','gm','accounts','manager','staff','supervisor','opm'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['form_action'] ?? '';
    if ($action === 'add') {
        $module = $_POST['module'];
        $stage = (int)$_POST['stage_order'];
        $role = $_POST['role_required'];
        $min = (float)($_POST['min_amount'] ?: 0);
        $max = $_POST['max_amount'] !== '' ? (float)$_POST['max_amount'] : null;
        $pdo->prepare("INSERT INTO approval_workflows (module, stage_order, role_required, min_amount, max_amount) VALUES (?,?,?,?,?)")
            ->execute([$module, $stage, $role, $min, $max]);
        flash('success', 'Workflow stage added.');
    } elseif ($action === 'toggle') {
        $pdo->prepare("UPDATE approval_workflows SET is_active = 1 - is_active WHERE id=?")->execute([$_POST['id']]);
    } elseif ($action === 'delete') {
        $pdo->prepare("DELETE FROM approval_workflows WHERE id=?")->execute([$_POST['id']]);
        flash('success', 'Stage removed.');
    }
    redirect('approval_workflow.php');
}

$prStages = $pdo->query("SELECT * FROM approval_workflows WHERE module='purchase_requisition' ORDER BY stage_order")->fetchAll();
$srStages = $pdo->query("SELECT * FROM approval_workflows WHERE module='store_requisition' ORDER BY stage_order")->fetchAll();

$pageTitle = 'Approval Workflow';
include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/sidebar.php';

function render_stage_table($stages) {
    echo '<div class="overflow-x-auto"><table class="w-full text-sm"><thead class="bg-slate-50 text-slate-500 text-xs uppercase"><tr>
      <th class="text-left px-5 py-2">Stage</th><th class="text-left px-5 py-2">Role Required</th>
      <th class="text-left px-5 py-2">Amount Range</th><th class="text-left px-5 py-2">Active</th>
      <th class="text-right px-5 py-2">Actions</th></tr></thead><tbody>';
    foreach ($stages as $s) {
        $range = '₦' . number_format($s['min_amount'],2) . ' - ' . ($s['max_amount'] !== null ? '₦'.number_format($s['max_amount'],2) : '∞');
        echo '<tr class="border-t border-slate-100">
          <td class="px-5 py-2.5">'.$s['stage_order'].'</td>
          <td class="px-5 py-2.5 capitalize">'.e($s['role_required']).'</td>
          <td class="px-5 py-2.5">'.$range.'</td>
          <td class="px-5 py-2.5">'.($s['is_active']?'Yes':'No').'</td>
          <td class="px-5 py-2.5 text-right space-x-2">
            <form method="POST" class="inline"><input type="hidden" name="form_action" value="toggle"><input type="hidden" name="id" value="'.$s['id'].'">
              <button class="text-blue-600 hover:underline">Toggle</button></form>
            <form method="POST" class="inline" onsubmit="return confirm(\'Remove this stage?\')"><input type="hidden" name="form_action" value="delete"><input type="hidden" name="id" value="'.$s['id'].'">
              <button class="text-red-600 hover:underline">Delete</button></form>
          </td></tr>';
    }
    if (empty($stages)) echo '<tr><td colspan="5" class="px-5 py-6 text-center text-slate-400">No stages configured.</td></tr>';
    echo '</tbody></table></div>';
}
?>
<h1 class="text-2xl font-bold mb-2">Approval Workflow Configuration</h1>
<p class="text-slate-500 text-sm mb-6">Define which role must approve at each stage. You can set amount-based thresholds (e.g. GM only approves above a certain value).</p>

<div class="bg-white rounded-xl shadow-sm border border-slate-200 p-5 mb-8">
  <h2 class="font-semibold mb-4">Add Workflow Stage</h2>
  <form method="POST" class="grid grid-cols-2 md:grid-cols-5 gap-3 items-end">
    <input type="hidden" name="form_action" value="add">
    <div>
      <label class="text-xs text-slate-500 block mb-1">Module</label>
      <select name="module" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
        <option value="purchase_requisition">Purchase Requisition</option>
        <option value="store_requisition">Store Requisition</option>
      </select>
    </div>
    <div>
      <label class="text-xs text-slate-500 block mb-1">Stage Order</label>
      <input type="number" min="1" name="stage_order" required class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
    </div>
    <div>
      <label class="text-xs text-slate-500 block mb-1">Role Required</label>
      <select name="role_required" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
        <?php foreach ($roles as $r): ?><option value="<?= $r ?>"><?= ucfirst($r) ?></option><?php endforeach; ?>
      </select>
    </div>
    <div>
      <label class="text-xs text-slate-500 block mb-1">Min Amount</label>
      <input type="number" step="0.01" name="min_amount" value="0" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
    </div>
    <div>
      <label class="text-xs text-slate-500 block mb-1">Max Amount (blank = no limit)</label>
      <input type="number" step="0.01" name="max_amount" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
    </div>
    <div class="col-span-2 md:col-span-5">
      <button class="bg-blue-700 hover:bg-blue-800 text-white text-sm font-medium px-4 py-2 rounded-lg">Add Stage</button>
    </div>
  </form>
</div>

<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
  <div class="bg-white rounded-xl shadow-sm border border-slate-200">
    <div class="px-5 py-4 border-b border-slate-200 font-semibold">Purchase Requisition Chain</div>
    <?php render_stage_table($prStages); ?>
  </div>
  <div class="bg-white rounded-xl shadow-sm border border-slate-200">
    <div class="px-5 py-4 border-b border-slate-200 font-semibold">Store Requisition Chain</div>
    <?php render_stage_table($srStages); ?>
  </div>
</div>
<?php include __DIR__ . '/includes/footer.php'; ?>
