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

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

// Create directory
$storeDir = dirname(__DIR__) . '/uploads/store';
if (!is_dir($storeDir)) { @mkdir($storeDir, 0777, true); }

$success=''; $error='';

// Handle upload
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['upload_file'])) {
    if (isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['file'];
        $name = $file['name'];
        $size = $file['size'];
        $tmp  = $file['tmp_name'];
        if ($size > 50*1024*1024) {
            $error = 'সর্বোচ্চ ৫০MB ফাইল অনুমোদিত';
        } else {
            // Keep original extension, sanitize name
            $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
            $base = preg_replace('/[^a-zA-Z0-9_\-\.]+/', '_', pathinfo($name, PATHINFO_FILENAME));
            $final = $base . '_' . date('Ymd_His') . '_' . substr(sha1(uniqid('', true)),0,6) . ($ext?'.'.$ext:'');
            $dest = $storeDir . '/' . $final;
            if (@move_uploaded_file($tmp, $dest)) {
                $success = 'ফাইল আপলোড সম্পন্ন: ' . htmlspecialchars($final);
            } else {
                $error = 'ফাইল আপলোড ব্যর্থ';
            }
        }
    } else {
        $error = 'ফাইল নির্বাচন করুন';
    }
}

// Handle delete
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['delete_file'])) {
    $file = basename($_POST['delete_file']);
    $path = $storeDir . '/' . $file;
    if (is_file($path)) {
        @unlink($path);
        $success = 'ফাইল ডিলিট হয়েছে';
    }
}

// List files
$files = [];
foreach (is_dir($storeDir) ? scandir($storeDir) : [] as $f) {
    if ($f==='.'||$f==='..') continue;
    $path = $storeDir . '/' . $f;
    if (is_file($path)) {
        $files[] = [
            'name' => $f,
            'size' => filesize($path),
            'mtime'=> filemtime($path),
            'url'  => '../uploads/store/' . rawurlencode($f)
        ];
    }
}
usort($files, function($a,$b){return $b['mtime'] <=> $a['mtime'];});
?>
<!DOCTYPE html>
<html lang="bn">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>স্টোর রুম</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body>
  <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
    <div class="container-fluid">
      <a class="navbar-brand" href="../index.php"><i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট</a>
      <div class="navbar-nav ms-auto">
        <a class="nav-link" href="../index.php"><i class="fas fa-home"></i> হোম</a>
        <a class="nav-link" href="../logout.php"><i class="fas fa-sign-out-alt"></i> লগআউট</a>
      </div>
    </div>
  </nav>

  <div class="container-fluid mt-4">
    <?php if ($success): ?><div class="alert alert-success"><?php echo $success; ?></div><?php endif; ?>
    <?php if ($error): ?><div class="alert alert-danger"><?php echo $error; ?></div><?php endif; ?>

    <div class="row g-3">
      <div class="col-lg-4">
        <div class="card">
          <div class="card-header"><strong>ফাইল আপলোড</strong></div>
          <div class="card-body">
            <form method="post" enctype="multipart/form-data">
              <div class="mb-3">
                <label class="form-label">ফাইল</label>
                <input type="file" class="form-control" name="file" required>
              </div>
              <button class="btn btn-primary" name="upload_file"><i class="fas fa-cloud-upload-alt"></i> আপলোড</button>
            </form>
          </div>
        </div>
      </div>

      <div class="col-lg-8">
        <div class="card">
          <div class="card-header"><strong>ফাইল তালিকা</strong></div>
          <div class="card-body">
            <?php if (empty($files)): ?>
              <div class="text-center text-muted">কোনো ফাইল নেই</div>
            <?php else: ?>
            <div class="table-responsive">
              <table class="table table-striped align-middle">
                <thead class="table-light"><tr><th>ফাইল</th><th>সাইজ</th><th>তারিখ</th><th style="width:120px">অ্যাকশন</th></tr></thead>
                <tbody>
                  <?php foreach ($files as $f): ?>
                  <tr>
                    <td><a href="<?php echo $f['url']; ?>" target="_blank"><i class="far fa-file"></i> <?php echo htmlspecialchars($f['name']); ?></a></td>
                    <td><?php echo number_format($f['size']/1024,1); ?> KB</td>
                    <td><?php echo date('d-m-Y H:i', $f['mtime']); ?></td>
                    <td>
                      <div class="btn-group btn-group-sm">
                        <a class="btn btn-outline-info" href="<?php echo $f['url']; ?>" target="_blank"><i class="fas fa-download"></i></a>
                        <form method="post" onsubmit="return confirm('ডিলিট করবেন?');">
                          <input type="hidden" name="delete_file" value="<?php echo htmlspecialchars($f['name']); ?>">
                          <button class="btn btn-outline-danger"><i class="fas fa-trash"></i></button>
                        </form>
                      </div>
                    </td>
                  </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
            <?php endif; ?>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>
</html>