<?php
session_start();
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}
include '../db.php';

// Fetch categories for dropdown
$categories = $pdo->query("SELECT id, name FROM categories")->fetchAll();

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name']);
    $website = trim($_POST['website']);
    $region = trim($_POST['region']);
    $category_id = intval($_POST['category_id']);
    $description = trim($_POST['description']);
    $imageName = '';

    if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
        $imageName = basename($_FILES['image']['name']);
        move_uploaded_file($_FILES['image']['tmp_name'], "../images/companies/" . $imageName);
    }

    $stmt = $pdo->prepare("INSERT INTO companies (name, website, region, image, category_id, description) VALUES (?,?,?,?,?,?)");
    $ok = $stmt->execute([$name, $website, $region, $imageName, $category_id, $description]);

    if ($ok) {
        $success = "Company added successfully!";
    } else {
        $error = "Failed to add company.";
    }
}
?>

<?php include 'menu.php'; ?>
<!DOCTYPE html>
<html>
<head>
    <title>Add Company</title>
    <link rel="stylesheet" href="../style.css">
    <style>
.container { max-width:400px; margin:2rem auto; }
form { display:flex; flex-direction:column; gap:0.8rem; }
input[type="text"], textarea, input[type="password"], select { padding:0.6rem; border-radius:6px; border:1px solid #ccc; }
button { padding:0.6rem; background:#007BFF; color:#fff; border:none; border-radius:6px; cursor:pointer; }
button:hover { background:#0056b3; }
</style>
</head>
<body>
<div class="container">
    <h2>Add New Company</h2>
    <?php if($success): ?><p style="color:green;"><?= htmlspecialchars($success) ?></p><?php endif; ?>
    <?php if($error): ?><p style="color:red;"><?= htmlspecialchars($error) ?></p><?php endif; ?>
    <form method="POST" enctype="multipart/form-data">
        <input type="text" name="name" placeholder="Company Name" required>
        <input type="text" name="website" placeholder="Website">
        <input type="text" name="region" placeholder="Region">
        <select name="category_id" required>
            <option value="">Select Category</option>
            <?php foreach($categories as $cat): ?>
                <option value="<?= $cat['id'] ?>"><?= htmlspecialchars($cat['name']) ?></option>
            <?php endforeach; ?>
        </select>
        <textarea name="description" placeholder="Company Description" rows="5"></textarea>
        <input type="file" name="image" accept="image/*">
        <button type="submit">Add Company</button>
    </form>
    <p><a href="dashboard.php">Back to Dashboard</a></p>
</div>
</body>
</html>
