<?php
// moh_submission.php
session_start();
require_once '../config.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

$role = $_SESSION['role'] ?? '';
$userid = (int)$_SESSION['user_id'];

function e($v){ return htmlspecialchars($v ?? '', ENT_QUOTES); }

// CSRF token
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(16));
}
$csrf = $_SESSION['csrf_token'];

$errors = [];
$messages = [];

/* Handle add submission */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_submission'])) {
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid CSRF token.';
    } else {
        $title = trim($_POST['title'] ?? '');
        $department = trim($_POST['department'] ?? '');
        $dossier = trim($_POST['dossier_number'] ?? '');
        $submission_date = trim($_POST['submission_date'] ?? '');
        $notes = trim($_POST['notes'] ?? '');

        if ($title === '') $errors[] = 'Title is required.';
        if ($submission_date === '') $errors[] = 'Submission date is required.';

        $attachment_path = null;
        // Handle file upload if provided
        if (!empty($_FILES['attachment']['name'])) {
            $f = $_FILES['attachment'];
            if ($f['error'] === UPLOAD_ERR_OK) {
                $allowed = ['application/pdf','application/msword','application/vnd.openxmlformats-officedocument.wordprocessingml.document','image/jpeg','image/png'];
                $finfo = finfo_open(FILEINFO_MIME_TYPE);
                $mime = finfo_file($finfo, $f['tmp_name']);
                finfo_close($finfo);

                if (!in_array($mime, $allowed)) {
                    $errors[] = 'Attachment must be PDF, DOC, DOCX, JPG or PNG.';
                } elseif ($f['size'] > 5 * 1024 * 1024) {
                    $errors[] = 'Attachment must be <= 5MB.';
                } else {
                    $ext = pathinfo($f['name'], PATHINFO_EXTENSION);
                    $fname = 'moh_' . time() . '_' . bin2hex(random_bytes(6)) . '.' . $ext;
                    $dest_dir = __DIR__ . '/uploads/moh_attachments/';
                    if (!is_dir($dest_dir)) mkdir($dest_dir, 0755, true);
                    $dest = $dest_dir . $fname;
                    if (move_uploaded_file($f['tmp_name'], $dest)) {
                        $attachment_path = 'uploads/moh_attachments/' . $fname;
                    } else {
                        $errors[] = 'Failed to save attachment.';
                    }
                }
            } else {
                $errors[] = 'Attachment upload error.';
            }
        }

        if (empty($errors)) {
            $stmt = $conn->prepare("INSERT INTO moh_submissions (user_id, title, department, dossier_number, submission_date, notes, attachment_path, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())");
            $stmt->bind_param("issssss", $userid, $title, $department, $dossier, $submission_date, $notes, $attachment_path);
            if ($stmt->execute()) {
                $messages[] = 'Submission saved successfully.';
                // regenerate CSRF to avoid duplicate post
                $_SESSION['csrf_token'] = bin2hex(random_bytes(16));
                $csrf = $_SESSION['csrf_token'];
            } else {
                $errors[] = 'Database error: ' . $stmt->error;
            }
            $stmt->close();
        }
    }
}

/* Handle delete (POST) */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_submission'])) {
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid CSRF token.';
    } else {
        $del_id = (int)$_POST['delete_id'];
        // Optionally check role/ownership
        $stmt = $conn->prepare("SELECT attachment_path, user_id FROM moh_submissions WHERE id = ?");
        $stmt->bind_param("i", $del_id);
        $stmt->execute();
        $res = $stmt->get_result();
        if ($row = $res->fetch_assoc()) {
            // Allow deletion if owner or admin role (example check)
            if ($row['user_id'] != $userid && $role !== 'admin') {
                $errors[] = 'Access denied to delete this submission.';
            } else {
                $stmt2 = $conn->prepare("DELETE FROM moh_submissions WHERE id = ?");
                $stmt2->bind_param("i", $del_id);
                if ($stmt2->execute()) {
                    // delete file if exists
                    if (!empty($row['attachment_path'])) {
                        $p = __DIR__ . '/' . $row['attachment_path'];
                        if (file_exists($p)) @unlink($p);
                    }
                    $messages[] = 'Submission deleted.';
                } else {
                    $errors[] = 'Delete failed: ' . $stmt2->error;
                }
                $stmt2->close();
            }
        } else {
            $errors[] = 'Submission not found.';
        }
        $stmt->close();
    }
}

/* Fetch all submissions (latest first) */
$submissions = [];
$q = "SELECT s.*, u.username
      FROM moh_submissions s
      LEFT JOIN users u ON u.id = s.user_id
      ORDER BY s.created_at DESC";
if ($res = $conn->query($q)) {
    while ($r = $res->fetch_assoc()) $submissions[] = $r;
    $res->free();
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>MOH To Government Submission</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
:root{
--primary:#2563eb;
--primary-dark:#1d4ed8;
--bg:#f4f7fb;
--card:#ffffff;
--text:#0f172a;
--muted:#64748b;
--border:#e5e7eb;
--danger:#dc2626;
}

/* ===== BODY ===== */
body{
margin:0;
font-family:Inter,Segoe UI,Arial,sans-serif;
background:
radial-gradient(circle at top left, rgba(37,99,235,.08), transparent 22%),
radial-gradient(circle at top right, rgba(15,23,42,.06), transparent 20%),
var(--bg);
padding:80px 24px 30px;
color:var(--text);
}

/* ===== CONTAINER ===== */
.container{
margin-left:260px;
}

/* ===== TITLE ===== */
.page-title{
font-size:24px;
font-weight:800;
margin-bottom:20px;
display:flex;
align-items:center;
gap:10px;
}

/* ===== CARD ===== */
.card{
background:rgba(255,255,255,.92);
backdrop-filter:blur(8px);
border:1px solid rgba(229,231,235,.9);
border-radius:24px;
box-shadow:0 18px 50px rgba(15,23,42,.10);
padding:24px;
margin-bottom:20px;
}

/* ===== FORM ===== */
.form-row{
display:grid;
grid-template-columns:repeat(2,1fr);
gap:16px;
}

.field{
display:flex;
flex-direction:column;
}

label{
font-size:13px;
font-weight:600;
margin-bottom:6px;
color:#334155;
}

input[type=text],
input[type=date],
textarea,
select{
width:100%;
padding:12px 14px;
border-radius:14px;
border:1px solid var(--border);
font-size:14px;
background:#fff;
transition:.2s;
}

input:focus,
textarea:focus,
select:focus{
border-color:#000;
outline:none;
}

textarea{
min-height:100px;
resize:vertical;
}

/* ===== BUTTON ===== */
.btn{
background:#000;
color:#fff;
padding:10px 16px;
border-radius:14px;
border:none;
font-weight:600;
cursor:pointer;
display:inline-flex;
align-items:center;
gap:8px;
transition:.2s;
}

.btn:hover{
transform:translateY(-1px);
background:linear-gradient(135deg,var(--primary-dark),#2563eb);
}

.btn.ghost{
background:#fff;
color:#111;
border:1px solid var(--border);
}

.btn.ghost:hover{
background:#f1f5f9;
}

/* ===== NOTICE ===== */
.notice{
padding:12px;
border-radius:10px;
margin-bottom:12px;
font-weight:500;
}

.notice.success{
background:#dcfce7;
color:#166534;
}

.notice.error{
background:#fee2e2;
color:#991b1b;
}

/* ===== TABLE ===== */
.table{
width:100%;
border-collapse:separate;
border-spacing:0 10px;
margin-top:12px;
}

.table th{
background:#374155;
color:#fff;
padding:14px;
font-size:13px;
text-align:left;
}

.table th:first-child{
border-radius:10px 0 0 10px;
}
.table th:last-child{
border-radius:0 10px 10px 0;
}

.table td{
background:#f9fbfd;
padding:14px;
font-size:14px;
border-top:1px solid var(--border);
border-bottom:1px solid var(--border);
}

/* rounded rows */
.table td:first-child{
border-left:1px solid var(--border);
border-radius:10px 0 0 10px;
}
.table td:last-child{
border-right:1px solid var(--border);
border-radius:0 10px 10px 0;
}

.table tr:hover td{
background:#eef2f7;
}

/* ===== ACTIONS ===== */
.actions{
display:flex;
gap:8px;
}

.small{
font-size:13px;
color:var(--muted);
}

/* ===== RESPONSIVE ===== */
@media(max-width:900px){
.container{margin-left:0;}
body{padding:70px 15px;}
.form-row{
grid-template-columns:1fr;
}
}
/* ================= MOBILE RESPONSIVE ================= */
@media (max-width:768px){

    /* 🔥 REMOVE SIDEBAR GAP */
    .container{
        margin-left:0 !important;
        padding:10px;
    }

    body{
        padding:65px 10px;
    }

    /* 🔥 HEADER */
    .page-title{
        font-size:18px;
        flex-direction:column;
        align-items:flex-start;
        gap:6px;
    }

    /* 🔥 FORM */
    .form-row{
        grid-template-columns:1fr;
        gap:10px;
    }

    input, textarea, select{
        font-size:13px;
    }

    /* BUTTON */
    .btn{
        width:100%;
        justify-content:center;
    }

    /* 🔥 TABLE → CARD */
    .table thead{
        display:none;
    }

    .table{
        border-spacing:0;
    }

    .table tbody tr{
        display:block;
        background:#fff;
        margin-bottom:12px;
        border-radius:12px;
        padding:12px;
        box-shadow:0 4px 10px rgba(0,0,0,0.05);
    }

    .table tbody td{
        display:flex;
        justify-content:space-between;
        align-items:flex-start;
        padding:8px 0;
        border:none;
        font-size:13px;
        gap:10px;
    }

    .table tbody td::before{
        content:attr(data-label);
        font-weight:600;
        color:#64748b;
        flex:0 0 45%;
    }

    /* ACTION */
    .actions{
        justify-content:flex-end;
        width:100%;
    }

}
</style>
</head>
<body>
<?php include 'rasidebar.php'; ?>
<?php include '../header.php'; ?>
<?php // you likely include your sidebar/nav here; omitted for brevity ?>

<div class="container">
  <div class="page-title" style="color:#000"><i class="fa fa-paper-plane"></i> MOH To Government Submission</div>

  <?php foreach ($messages as $m): ?>
    <div class="notice success"><?php echo e($m); ?></div>
  <?php endforeach; ?>
  <?php foreach ($errors as $er): ?>
    <div class="notice error"><?php echo e($er); ?></div>
  <?php endforeach; ?>

  <div class="card">
    <form method="post" enctype="multipart/form-data" novalidate>
      <input type="hidden" name="csrf_token" value="<?php echo e($csrf); ?>">
      <div style="display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:12px;">
        <div style="font-weight:600;">Create new submission</div>
        <div><button class="btn" type="submit" name="add_submission"><i class="fa fa-plus"></i> Submit</button></div>
      </div>

      <div class="form-row" style="margin-top:12px;">
        <div class="field">
          <label>Title</label>
          <input type="text" name="title" required value="<?php echo e($_POST['title'] ?? ''); ?>">
        </div>
        <div class="field">
          <label>Department / Recipient</label>
          <input type="text" name="department" value="<?php echo e($_POST['department'] ?? 'Ministry of Health'); ?>">
        </div>
        <div class="field">
          <label>Dossier Number</label>
          <input type="text" name="dossier_number" value="<?php echo e($_POST['dossier_number'] ?? ''); ?>">
        </div>
        <div class="field">
          <label>Submission Date</label>
          <input type="date" name="submission_date" required value="<?php echo e($_POST['submission_date'] ?? date('Y-m-d')); ?>">
        </div>
      </div>

      <div style="margin-top:12px;">
        <label>Notes</label>
        <textarea name="notes"><?php echo e($_POST['notes'] ?? ''); ?></textarea>
      </div>

      <div style="margin-top:12px;">
        <label>Attachment (PDF / DOC / JPG / PNG, ≤5MB)</label>
        <input type="file" name="attachment" accept=".pdf,.doc,.docx,.jpg,.jpeg,.png">
      </div>
    </form>
  </div>

  <div class="card">
    <div style="display:flex; justify-content:space-between; align-items:center;">
      <div style="font-weight:600;">All submissions</div>
      <div class="small">Total: <?php echo count($submissions); ?></div>
    </div>

    <table class="table" style="margin-top:12px;">
      <thead>
        <tr>
          <th>No.</th>
          <th>Title / Notes</th>
          <th>Department</th>
          <th>Dossier</th>
          <th>Submitted On</th>
          <th>By</th>
          <th>Attachment</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
      <?php if (empty($submissions)): ?>
        <tr><td colspan="8" class="small">No submissions yet.</td></tr>
      <?php else: ?>
        <?php $i = 1; foreach ($submissions as $s): ?>
          <tr>
           <td data-label="No."><?php echo $i++; ?></td>

<td data-label="Title / Notes">
    <div style="font-weight:600;"><?php echo e($s['title']); ?></div>
    <div class="small"><?php echo e(mb_strimwidth($s['notes'], 0, 140, '...')); ?></div>
</td>

<td data-label="Department"><?php echo e($s['department']); ?></td>

<td data-label="Dossier"><?php echo e($s['dossier_number']); ?></td>

<td data-label="Submitted On">
    <?php echo e(date('Y-m-d', strtotime($s['submission_date']))); ?>
</td>

<td data-label="By"><?php echo e($s['username'] ?? '—'); ?></td>

<td data-label="Attachment">
    <?php if (!empty($s['attachment_path'])): ?>
        <a href="<?php echo e($s['attachment_path']); ?>" target="_blank">View</a>
    <?php else: ?>—<?php endif; ?>
</td>
            <td class="actions">
              <!-- Example: allow delete if owner or admin -->
              <?php if ($s['user_id'] == $userid || $role === 'admin'): ?>
                <form method="post" style="display:inline;">
                  <input type="hidden" name="csrf_token" value="<?php echo e($csrf); ?>">
                  <input type="hidden" name="delete_id" value="<?php echo e($s['id']); ?>">
                  <button class="btn ghost" type="submit" name="delete_submission" onclick="return confirm('Delete this submission?');"><i class="fa fa-trash"></i> Delete</button>
                </form>
              <?php else: ?>
                <span class="small">—</span>
              <?php endif; ?>
            </td>
          </tr>
        <?php endforeach; ?>
      <?php endif; ?>
      </tbody>
    </table>
  </div>

</div>
</body>
</html>