<?php
session_start();
include '../db.php';

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}

// Get company ID from URL
$id = intval($_GET['id'] ?? 0);

// Fetch existing company data
$stmt = $pdo->prepare("SELECT * FROM companies WHERE id = ?");
$stmt->execute([$id]);
$company = $stmt->fetch();

if (!$company) {
    die('Company not found!');
}

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

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name']);
    $website = trim($_POST['website']);
    $region = trim($_POST['region']);
    $category_id = intval($_POST['category_id']) ?: null;
    $description = trim($_POST['description']);

    // File upload handling
    $image = $company['image']; // keep current image by default
    if (!empty($_FILES['image']['name'])) {
        $uploadDir = '../images/companies/';
        $newImage = basename($_FILES['image']['name']);
        $targetFile = $uploadDir . $newImage;

        // Move uploaded file
        if (move_uploaded_file($_FILES['image']['tmp_name'], $targetFile)) {
            $image = $newImage;
        }
    }

    // Update database, now including description
    $update = $pdo->prepare("
        UPDATE companies
        SET name = ?, website = ?, region = ?, category_id = ?, image = ?, description = ?
        WHERE id = ?
    ");
    $update->execute([$name, $website, $region, $category_id, $image, $description, $id]);

    header('Location: edit_company.php?success=1');
    exit;
}
?>

<?php include 'menu.php'; ?>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Edit Company - Admin</title>
<link rel="stylesheet" href="../style.css">
<style>
    .container { max-width:400px; margin:2rem auto; }
    form { display:flex; flex-direction:column; gap:0.8rem; }
    label { font-weight: bold; }
    input[type="text"], select, textarea { 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>Edit Company: <?= htmlspecialchars($company['name']) ?></h2>
    <form method="post" enctype="multipart/form-data">
        <label>Name:</label>
        <input type="text" name="name" value="<?= htmlspecialchars($company['name']) ?>" required>

        <label>Website:</label>
        <input type="text" name="website" value="<?= htmlspecialchars($company['website']) ?>">

        <label>Region:</label>
        <input type="text" name="region" value="<?= htmlspecialchars($company['region']) ?>">

        <label>Category:</label>
        <select name="category_id">
            <option value="">-- None --</option>
            <?php foreach ($categories as $cat): ?>
                <option value="<?= $cat['id'] ?>" <?= ($cat['id'] == $company['category_id']) ? 'selected' : '' ?>>
                    <?= htmlspecialchars($cat['name']) ?>
                </option>
            <?php endforeach; ?>
        </select>

        <label>Description:</label>
        <textarea name="description" rows="4"><?= htmlspecialchars($company['description']) ?></textarea>

        <label>Current Image:</label>
        <?php if ($company['image']): ?>
            <img src="../images/companies/<?= htmlspecialchars($company['image']) ?>" alt="Company Image" style="width:100px;">
        <?php else: ?>
            <p>No image uploaded</p>
        <?php endif; ?>

        <label>Upload New Image (optional):</label>
        <input type="file" name="image">

        <button type="submit">Update Company</button>
    </form>
    <p><a href="edit_company.php">← Back to Companies</a></p>
</div>
</body>
</html>
