<?php
declare(strict_types=1);

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/inc/auth.php';

require_once __DIR__ . '/inc/layout.php';

if (empty($_SESSION['user_id'])) {
    header("Location: index.html?e=1");
    exit;
}

function get_pdo(): PDO
{
    if (function_exists('db')) {
        $pdo = db();
        if ($pdo instanceof PDO) return $pdo;
    }

    if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) {
        return $GLOBALS['pdo'];
    }

    throw new RuntimeException('DB not ready: PDO not found. Ensure db.php defines db():PDO or $pdo');
}

$pdo = get_pdo();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

$role            = strtoupper((string)($_SESSION['role'] ?? 'STAFF'));
$sessionBranchId = (int)($_SESSION['branch_id'] ?? 1);
$userName        = (string)($_SESSION['name'] ?? $_SESSION['username'] ?? 'مستخدم');

/* تعريب الحالات */
$TASK_STATUS = [
    'OPEN'   => 'مفتوحة',
    'DONE'   => 'قيد التنفيذ',
    'CLOSED' => 'مغلقة',
    'NEW'    => 'مفتوحة',
];

/* تعريب الأولويات */
$TASK_PRIORITY = [
    'HIGH'   => 'عالية',
    'MEDIUM' => 'متوسطة',
    'LOW'    => 'منخفضة',
];

/* اسم الفرع */
try {
    $stB = $pdo->prepare("SELECT name_ar FROM branches WHERE id = ? LIMIT 1");
    $stB->execute([$sessionBranchId]);
    $currentBranchName = (string)($stB->fetchColumn() ?: 'أبوظبي');
} catch (Throwable $e) {
    $currentBranchName = match ($sessionBranchId) {
        2 => 'دبي',
        3 => 'الشارقة',
        default => 'أبوظبي',
    };
}

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) {
    header("Location: " . u('tasks.php?e=missing_id'));
    exit;
}

/* اجلب المهمة */
$st = $pdo->prepare("
    SELECT id, branch_id, title, status, priority, due_date, created_at
    FROM tasks
    WHERE id = ?
    LIMIT 1
");
$st->execute([$id]);
$task = $st->fetch();

if (!$task) {
    header("Location: " . u('tasks.php?e=not_found'));
    exit;
}

$taskBranchId = (int)($task['branch_id'] ?? 0);

/* صلاحيات التعديل */
if (!in_array($role, ['OWNER', 'ADMIN'], true)) {
    if ($taskBranchId !== $sessionBranchId) {
        header("Location: " . u('tasks.php?e=forbidden'));
        exit;
    }
}

$msg = '';
$err = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title    = trim((string)($_POST['title'] ?? ''));
    $status   = strtoupper(trim((string)($_POST['status'] ?? 'OPEN')));
    $priority = strtoupper(trim((string)($_POST['priority'] ?? 'MEDIUM')));
    $dueDate  = trim((string)($_POST['due_date'] ?? ''));

    $allowedS = array_keys($TASK_STATUS);
    if (!in_array($status, $allowedS, true)) {
        $status = 'OPEN';
    }

    $allowedP = array_keys($TASK_PRIORITY);
    if (!in_array($priority, $allowedP, true)) {
        $priority = 'MEDIUM';
    }

    $due = ($dueDate !== '') ? $dueDate : null;

    if ($title === '') {
        $err = 'الرجاء كتابة عنوان المهمة.';
    } else {
        try {
            $up = $pdo->prepare("
                UPDATE tasks
                SET title = ?, status = ?, priority = ?, due_date = ?
                WHERE id = ?
                LIMIT 1
            ");
            $up->execute([$title, $status, $priority, $due, $id]);

            $msg = 'تم حفظ التعديلات بنجاح.';

            $st->execute([$id]);
            $task = $st->fetch() ?: $task;
        } catch (Throwable $e) {
            $err = 'حدث خطأ أثناء الحفظ.';
        }
    }
}
if (function_exists('log_employee_achievement')) {
    log_employee_achievement(
        $pdo,
        'تعديل مهمة',
        'تم تعديل المهمة: ' . $title .
        ($taskId > 0 ? ' | رقم المهمة: ' . $taskId : '') .
        ($employeeId > 0 ? ' | للموظف رقم: ' . $employeeId : '')
    );
}
render_layout_start('تعديل مهمة');
?>

<style>
  :root{
    --bg-main:#07171d;
    --bg-card:rgba(255,255,255,.05);
    --bg-card-2:rgba(255,255,255,.04);
    --line:rgba(255,255,255,.08);
    --line-soft:rgba(255,255,255,.05);
    --text:#ffffff;
    --muted:rgba(255,255,255,.68);
    --gold:#d4af37;
    --gold-2:#ffd76a;
    --gold-soft:rgba(212,175,55,.14);
    --danger:#f87171;
    --danger-soft:rgba(248,113,113,.12);
    --success:#34d399;
    --success-soft:rgba(52,211,153,.12);
    --shadow:0 18px 40px rgba(0,0,0,.16);
  }

  body{
    background:
      radial-gradient(circle at 20% 20%, rgba(10,77,87,.85), transparent 40%),
      radial-gradient(circle at 80% 80%, rgba(13,106,122,.55), transparent 40%),
      #021d23;
  }

  .task-edit-page{
    color:var(--text);
    width:100%;
    max-width:100%;
  }

  .task-edit-page *{
    box-sizing:border-box;
  }

  .task-edit-page .topbar-local{
    min-height:68px;
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:14px;
    padding:10px 12px;
    background:var(--bg-card);
    border:1px solid var(--line);
    border-radius:18px;
    box-shadow:var(--shadow);
    position:sticky;
    top:12px;
    z-index:10;
    margin-bottom:18px;
    backdrop-filter:blur(12px);
    flex-wrap:wrap;
  }

  .task-edit-page .branch-badge{
    display:flex;
    align-items:center;
    gap:8px;
    background:rgba(255,255,255,.05);
    border:1px solid var(--line);
    border-radius:999px;
    padding:10px 12px;
    box-shadow:0 8px 18px rgba(0,0,0,.10);
    font-weight:800;
    color:#fff;
    backdrop-filter:blur(8px);
  }

  .task-edit-page .dot{
    width:8px;
    height:8px;
    border-radius:50%;
    background:var(--gold);
    box-shadow:0 0 0 4px rgba(212,175,55,.14);
  }

  .task-edit-page .btn{
    display:inline-flex;
    align-items:center;
    gap:8px;
    height:40px;
    padding:0 14px;
    border-radius:999px;
    border:1px solid rgba(212,175,55,.25);
    background:linear-gradient(135deg,#ffd76a,#d4af37);
    font-weight:900;
    color:#1d1600;
    cursor:pointer;
    text-decoration:none;
    font-family:inherit;
    box-shadow:0 12px 24px rgba(212,175,55,.18);
    transition:.18s ease;
  }

  .task-edit-page .btn:hover{
    transform:translateY(-2px);
    box-shadow:0 16px 28px rgba(212,175,55,.24);
  }

  .task-edit-page .btnPrimary{
    background:linear-gradient(135deg,#ffd76a,#d4af37);
    border:1px solid rgba(212,175,55,.25);
    color:#1d1600;
  }

  .task-edit-page .btnDanger{
    border:1px solid rgba(248,113,113,.22);
    background:rgba(248,113,113,.08);
    color:#fca5a5;
    box-shadow:none;
  }

  .task-edit-page .btnDanger:hover{
    background:rgba(248,113,113,.14);
    transform:translateY(-1px);
  }

  .task-edit-page .page-head{
    margin:18px 6px 14px;
    display:flex;
    align-items:flex-end;
    justify-content:space-between;
    gap:12px;
    flex-wrap:wrap;
  }

  .task-edit-page .pageTitle{
    font-size:30px;
    font-weight:900;
    color:#ffffff;
    margin:0;
    line-height:1.1;
  }

  .task-edit-page .pageSub{
    color:rgba(255,255,255,.72);
    font-size:14px;
    line-height:1.8;
    margin-top:6px;
  }

  .task-edit-page .card{
    background:var(--bg-card);
    border:1px solid var(--line);
    border-radius:18px;
    box-shadow:var(--shadow);
    overflow:hidden;
    padding:16px;
    max-width:980px;
    margin:0 auto;
    backdrop-filter:blur(12px);
  }

  .task-edit-page .grid{
    display:grid;
    grid-template-columns:repeat(3, minmax(0,1fr));
    gap:12px;
  }

  .task-edit-page label{
    display:block;
    margin-bottom:6px;
    font-weight:800;
    color:#ffffff;
  }

  .task-edit-page input,
  .task-edit-page select{
    width:100%;
    height:44px;
    border-radius:14px;
    border:1px solid var(--line);
    padding:0 12px;
    outline:none;
    background:rgba(255,255,255,.05);
    font-family:inherit;
    color:#fff;
    box-shadow:none;
  }

  .task-edit-page input::placeholder{
    color:rgba(255,255,255,.45);
  }

  .task-edit-page select option{
    background:#0b1f26;
    color:#fff;
  }

  .task-edit-page input:focus,
  .task-edit-page select:focus{
    border-color:rgba(212,175,55,.45);
    box-shadow:0 0 0 4px rgba(212,175,55,.12);
    background:rgba(255,255,255,.06);
  }

  .task-edit-page .msg{
    max-width:980px;
    margin:10px auto 0;
    padding:12px 14px;
    border-radius:14px;
    border:1px solid var(--line);
    background:rgba(255,255,255,.05);
    line-height:1.8;
  }

  .task-edit-page .ok{
    border-color:rgba(52,211,153,.24);
    background:rgba(6,95,70,.18);
    color:#d1fae5;
  }

  .task-edit-page .err{
    border-color:rgba(248,113,113,.24);
    background:rgba(127,29,29,.18);
    color:#fecaca;
  }

  .task-edit-page .actions{
    display:flex;
    gap:10px;
    flex-wrap:wrap;
    margin-top:14px;
  }

  .task-edit-page .footerNote{
    max-width:980px;
    margin:18px auto 0;
    padding:14px 18px;
    border-radius:16px;
    background:rgba(255,255,255,.04);
    border:1px solid rgba(255,255,255,.08);
    backdrop-filter:blur(8px);
    color:rgba(255,255,255,.75);
    font-size:13px;
  }

  .task-edit-page .footer-inner{
    display:flex;
    justify-content:space-between;
    align-items:center;
    flex-wrap:wrap;
    gap:10px;
  }

  .task-edit-page .footer-copy{
    color:#ffd76a !important;
    font-weight:700;
    letter-spacing:.3px;
  }

  .task-edit-page .footer-system{
    font-weight:800;
    color:#d4af37;
    letter-spacing:.5px;
  }

  @media (max-width:980px){
    .task-edit-page .grid{
      grid-template-columns:1fr;
    }
  }

  @media (max-width:700px){
    .task-edit-page .footer-inner{
      flex-direction:column;
      text-align:center;
    }

    .task-edit-page .pageTitle{
      font-size:24px;
    }
  }
</style>

<div class="task-edit-page">
  <div class="topbar-local">
    <div class="branch-badge">
      <span class="dot"></span>
      <span><?= h($currentBranchName) ?></span>
    </div>

    <a class="btn" href="<?= h(u('tasks.php')) ?>">رجوع</a>
  </div>

  <div class="page-head">
    <div>
      <h1 class="pageTitle">تعديل مهمة</h1>
      <div class="pageSub">تعديل المهمة داخل فرعها</div>
    </div>
    <div class="pageSub">رقم المهمة: <?= (int)$task['id'] ?></div>
  </div>

  <?php if ($msg !== ''): ?>
    <div class="msg ok"><?= h($msg) ?></div>
  <?php endif; ?>

  <?php if ($err !== ''): ?>
    <div class="msg err"><?= h($err) ?></div>
  <?php endif; ?>

  <form class="card" method="post">
    <div class="grid">
      <div style="grid-column:1/-1;">
        <label>عنوان المهمة</label>
        <input name="title" required value="<?= h((string)($task['title'] ?? '')) ?>" placeholder="اكتب عنوان المهمة...">
      </div>

      <div>
        <label>الحالة</label>
        <?php $curS = strtoupper((string)($task['status'] ?? 'OPEN')); ?>
        <select name="status">
          <?php foreach ($TASK_STATUS as $code => $label): ?>
            <option value="<?= h($code) ?>" <?= $curS === $code ? 'selected' : '' ?>>
              <?= h($label) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>

      <div>
        <label>الأولوية</label>
        <?php $curP = strtoupper((string)($task['priority'] ?? 'MEDIUM')); ?>
        <select name="priority">
          <?php foreach ($TASK_PRIORITY as $pCode => $pLabel): ?>
            <option value="<?= h($pCode) ?>" <?= $curP === $pCode ? 'selected' : '' ?>>
              <?= h($pLabel) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>

      <div>
        <label>تاريخ الاستحقاق (اختياري)</label>
        <input type="date" name="due_date" value="<?= h((string)($task['due_date'] ?? '')) ?>">
      </div>
    </div>

    <div class="actions">
      <button class="btn btnPrimary" type="submit">حفظ التعديلات</button>
      <a class="btn btnDanger" href="<?= h(u('task_delete.php?id=' . (int)$task['id'])) ?>" onclick="return confirm('هل أنت متأكد من حذف المهمة؟');">حذف المهمة</a>
    </div>
  </form>
</div>

<?php render_layout_end(); ?>