<?php
require_once __DIR__ . '/../includes/auth.php';
requireLogin();
requirePermission('projects.manage');

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/layout.php';

$userId = $_SESSION['user_id'];

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$projectId = isset($_GET['project_id']) ? (int)$_GET['project_id'] : 0;

if ($id <= 0) {
    die("Invalid task ID.");
}

/* ================= FETCH TASK ================= */
$stmt = $pdo->prepare("SELECT * FROM project_tasks WHERE id = ?");
$stmt->execute([$id]);
$task = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$task) {
    die("Task not found.");
}

/* ================= HANDLE UPDATE ================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $fieldsToTrack = ['description','priority','status','due_date','quantity','unit_cost','unit_price'];
    $newValues = [
        'description' => $_POST['description'],
        'priority'    => $_POST['priority'],
        'status'      => $_POST['status'],
        'due_date'    => $_POST['due_date'] ?: null,
        'quantity'    => (int)$_POST['quantity'],
        'unit_cost'   => (float)$_POST['unit_cost'],
        'unit_price'  => (float)$_POST['unit_price']
    ];

    /* ===== DEPENDENCY CHECK ===== */
    if ($newValues['status'] === 'IN_PROGRESS' && $task['depends_on_task_id']) {
        $depStmt = $pdo->prepare("SELECT status FROM project_tasks WHERE id = ?");
        $depStmt->execute([$task['depends_on_task_id']]);
        $dep = $depStmt->fetchColumn();
        if ($dep !== 'COMPLETED') {
            die("Cannot start this task until dependency is completed.");
        }
    }

    /* ===== UPDATE TASK ===== */
    $updateStmt = $pdo->prepare("
        UPDATE project_tasks
        SET description = ?,
            priority = ?,
            status = ?,
            due_date = ?,
            quantity = ?,
            unit_cost = ?,
            unit_price = ?
        WHERE id = ?
    ");

    $updateStmt->execute([
        $newValues['description'],
        $newValues['priority'],
        $newValues['status'],
        $newValues['due_date'],
        $newValues['quantity'],
        $newValues['unit_cost'],
        $newValues['unit_price'],
        $id
    ]);

    /* ===== HISTORY LOGGING ===== */
    foreach ($fieldsToTrack as $field) {
        if ($task[$field] != $newValues[$field]) {
            $logStmt = $pdo->prepare("
                INSERT INTO task_history (task_id, changed_by_user_id, field_name, old_value, new_value)
                VALUES (?, ?, ?, ?, ?)
            ");
            $logStmt->execute([
                $id,
                $userId,
                $field,
                $task[$field],
                $newValues[$field]
            ]);
        }
    }

    /* ===== FILE UPLOAD ===== */
    if (!empty($_FILES['attachment']['name'])) {
        $uploadDir = __DIR__ . '/../uploads/tasks/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        $fileName = time() . '_' . basename($_FILES['attachment']['name']);
        $targetPath = $uploadDir . $fileName;

        if (move_uploaded_file($_FILES['attachment']['tmp_name'], $targetPath)) {
            $attachStmt = $pdo->prepare("
                INSERT INTO task_attachments (task_id, file_name, file_path, uploaded_by_user_id)
                VALUES (?, ?, ?, ?)
            ");
            $attachStmt->execute([$id, $fileName, $targetPath, $userId]);
        }
    }

    header("Location: project_view.php?id=" . $projectId);
    exit;
}

/* ================= FETCH HISTORY ================= */
$historyStmt = $pdo->prepare("SELECT th.*, u.full_name 
                              FROM task_history th
                              LEFT JOIN users u ON th.changed_by_user_id = u.id
                              WHERE task_id = ?
                              ORDER BY th.created_at DESC");
$historyStmt->execute([$id]);
$history = $historyStmt->fetchAll(PDO::FETCH_ASSOC);

/* ================= FETCH ATTACHMENTS ================= */
$attachStmt = $pdo->prepare("SELECT * FROM task_attachments WHERE task_id = ?");
$attachStmt->execute([$id]);
$attachments = $attachStmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="main-content">

  <div class="page-header">
    <h2>Edit Task</h2>
    <p class="page-subtitle">
      Task ID: <strong>#<?= (int)$task['id'] ?></strong>
    </p>
  </div>

  <form method="POST" enctype="multipart/form-data" class="card-form" style="max-width:820px;">

    <label>Description</label>
    <textarea name="description" rows="3" required><?= htmlspecialchars($task['description']) ?></textarea>

    <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">

      <div>
        <label>Status</label>
        <select name="status">
          <option value="PENDING" <?= $task['status']=='PENDING'?'selected':'' ?>>Pending</option>
          <option value="ASSIGNED" <?= $task['status']=='ASSIGNED'?'selected':'' ?>>Assigned</option>
          <option value="IN_PROGRESS" <?= $task['status']=='IN_PROGRESS'?'selected':'' ?>>In Progress</option>
          <option value="COMPLETED" <?= $task['status']=='COMPLETED'?'selected':'' ?>>Completed</option>
          <option value="CANCELLED" <?= $task['status']=='CANCELLED'?'selected':'' ?>>Cancelled</option>
        </select>
      </div>

      <div>
        <label>Priority</label>
        <select name="priority">
          <option value="LOW" <?= $task['priority']=='LOW'?'selected':'' ?>>Low</option>
          <option value="NORMAL" <?= $task['priority']=='NORMAL'?'selected':'' ?>>Normal</option>
          <option value="HIGH" <?= $task['priority']=='HIGH'?'selected':'' ?>>High</option>
          <option value="URGENT" <?= $task['priority']=='URGENT'?'selected':'' ?>>Urgent</option>
        </select>
      </div>

    </div>

    <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">

      <div>
        <label>Quantity</label>
        <input type="number" name="quantity" value="<?= htmlspecialchars($task['quantity']) ?>">
      </div>

      <div>
        <label>Due Date</label>
        <input type="date" name="due_date" value="<?= htmlspecialchars($task['due_date']) ?>">
      </div>

    </div>

    <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">

      <div>
        <label>Unit Cost</label>
        <input type="number" step="0.01" name="unit_cost" value="<?= htmlspecialchars($task['unit_cost']) ?>">
      </div>

      <div>
        <label>Unit Price</label>
        <input type="number" step="0.01" name="unit_price" value="<?= htmlspecialchars($task['unit_price']) ?>">
      </div>

    </div>

    <label>Upload Attachment (optional)</label>
    <input type="file" name="attachment">

    <div style="margin-top:14px;display:flex;gap:10px;">
      <button type="submit" class="btn-primary">Update Task</button>
      <a class="btn-secondary" href="project_view.php?id=<?= (int)$projectId ?>">Cancel</a>
    </div>

  </form>

  <!-- ================= HISTORY ================= -->

  <div class="card-form" style="max-width:820px;margin-top:20px;">
    <h3>History Log</h3>

    <?php if (empty($history)): ?>
      <p style="opacity:0.6;">No changes recorded yet.</p>
    <?php else: ?>
      <?php foreach ($history as $h): ?>
        <div style="padding:8px 0;border-bottom:1px solid #eee;">
          <strong><?= htmlspecialchars($h['full_name'] ?? 'System') ?></strong>
          changed <strong><?= htmlspecialchars($h['field_name']) ?></strong>
          from "<span style="color:#dc2626"><?= htmlspecialchars($h['old_value']) ?></span>"
          to "<span style="color:#16a34a"><?= htmlspecialchars($h['new_value']) ?></span>"
          <div style="font-size:12px;opacity:0.6;">
            <?= htmlspecialchars($h['created_at']) ?>
          </div>
        </div>
      <?php endforeach; ?>
    <?php endif; ?>
  </div>

  <!-- ================= ATTACHMENTS ================= -->

  <div class="card-form" style="max-width:820px;margin-top:20px;">
    <h3>Attachments</h3>

    <?php if (empty($attachments)): ?>
      <p style="opacity:0.6;">No attachments uploaded.</p>
    <?php else: ?>
      <?php foreach ($attachments as $a): ?>
        <div style="padding:6px 0;">
          <a href="<?= str_replace(__DIR__.'/../','',$a['file_path']) ?>" target="_blank">
            <?= htmlspecialchars($a['file_name']) ?>
          </a>
        </div>
      <?php endforeach; ?>
    <?php endif; ?>
  </div>

</div>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>