<?php
require_once 'includes/header.php';

$pdo = db();
$error = '';
$success = '';

// Handle Delete
if (isset($_POST['delete_car'])) {
    $id = $_POST['car_id'];
    $stmt = $pdo->prepare("DELETE FROM cars WHERE id = ?");
    $stmt->execute([$id]);
    $success = "Car deleted successfully.";
}

// Handle Add (Basic Implementation)
if (isset($_POST['add_car'])) {
    try {
        $image_url = 'assets/images/cars/default.jpg'; // Default
        
        // Handle Image Upload
        if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = __DIR__ . '/../assets/images/cars/';
            if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
            
            $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
            $filename = uniqid('car_') . '.' . $ext;
            $targetPath = $uploadDir . $filename;
            
            if (move_uploaded_file($_FILES['image']['tmp_name'], $targetPath)) {
                $image_url = 'assets/images/cars/' . $filename;
            }
        }

        $stmt = $pdo->prepare("INSERT INTO cars (vin, brand, model, year, price, mileage, transmission, fuel_type, status, branch_id, dealer_id, installment_available, image_url) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'Available', ?, ?, ?, ?)");
        $stmt->execute([
            $_POST['vin'], $_POST['brand'], $_POST['model'], $_POST['year'], 
            $_POST['price'], $_POST['mileage'], $_POST['transmission'], 
            $_POST['fuel_type'], $_POST['branch_id'], $_POST['dealer_id'] ?: null, 
            isset($_POST['installment_available']) ? 1 : 0,
            $image_url
        ]);
        
        // Log activity
        $adminId = $_SESSION['user_id'];
        $pdo->prepare("INSERT INTO activity_logs (user_id, action) VALUES (?, 'Added new car: ' . ?)")->execute([$adminId, $_POST['brand'] . ' ' . $_POST['model']]);
        
        $success = "Car added successfully.";
    } catch (PDOException $e) {
        $error = "Error adding car: " . $e->getMessage();
    }
}

$branches = $pdo->query("SELECT * FROM branches")->fetchAll();
$dealers = $pdo->query("SELECT * FROM users WHERE role = 'Dealer'")->fetchAll();

$stmt = $pdo->query("SELECT cars.*, branches.name as branch_name FROM cars LEFT JOIN branches ON cars.branch_id = branches.id ORDER BY cars.created_at DESC");
$cars = $stmt->fetchAll();
?>

<div class="page-header">
    <h1>Car Management</h1>
    <button onclick="document.getElementById('addCarModal').style.display='block'" class="btn-sm btn-primary" style="background:var(--accent-color); color:var(--bg-color); border:none; padding:0.5rem 1rem; cursor:pointer;">Add New Car</button>
</div>

<?php if ($error): ?><div style="color: #ff4444; margin-bottom: 1rem;"><?php echo htmlspecialchars($error); ?></div><?php endif; ?>
<?php if ($success): ?><div style="color: #00C851; margin-bottom: 1rem;"><?php echo htmlspecialchars($success); ?></div><?php endif; ?>

<div style="overflow-x: auto;">
    <table class="data-table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Brand/Model</th>
                <th>Year</th>
                <th>Price</th>
                <th>Status</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($cars as $car): ?>
            <tr>
                <td>#<?php echo $car['id']; ?></td>
                <td><?php echo htmlspecialchars($car['brand'] . ' ' . $car['model']); ?></td>
                <td><?php echo $car['year']; ?></td>
                <td>$<?php echo number_format($car['price']); ?></td>
                <td><?php echo $car['status']; ?></td>
                <td>
                    <form method="POST" onsubmit="return confirm('Delete this car?');" style="display: inline;">
                        <input type="hidden" name="car_id" value="<?php echo $car['id']; ?>">
                        <button type="submit" name="delete_car" class="btn-sm btn-danger">Delete</button>
                    </form>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<!-- Simple Add Car Modal -->
<div id="addCarModal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.8); z-index:2000; align-items:center; justify-content:center; display:none;">
    <div style="background:var(--card-bg); margin:5% auto; padding:2rem; width:90%; max-width:500px; border-radius:12px; border:1px solid var(--border-color); position: relative; max-height: 90vh; overflow-y: auto;">
        <h2 style="margin-bottom:1.5rem; text-align:center;">Add New Car</h2>
        <form method="POST" enctype="multipart/form-data">
            <div style="margin-bottom:1rem;">
                <label style="display:block; margin-bottom:0.5rem;">Vehicle Image</label>
                <input type="file" name="image" accept="image/*" required style="width:100%; padding:0.8rem; background:var(--bg-color); border:1px solid var(--border-color); color:white; border-radius:4px;">
            </div>
            <div style="margin-bottom:1rem;">
                <input type="text" name="vin" placeholder="VIN Number" required style="width:100%; padding:0.8rem; background:var(--bg-color); border:1px solid var(--border-color); color:white; border-radius:4px;">
            </div>
            <div style="display:grid; grid-template-columns: 1fr 1fr; gap:1rem; margin-bottom:1rem;">
                <input type="text" name="brand" placeholder="Brand" required style="width:100%; padding:0.8rem; background:var(--bg-color); border:1px solid var(--border-color); color:white; border-radius:4px;">
                <input type="text" name="model" placeholder="Model" required style="width:100%; padding:0.8rem; background:var(--bg-color); border:1px solid var(--border-color); color:white; border-radius:4px;">
            </div>
            <div style="display:grid; grid-template-columns: 1fr 1fr; gap:1rem; margin-bottom:1rem;">
                <input type="number" name="year" placeholder="Year" required style="width:100%; padding:0.8rem; background:var(--bg-color); border:1px solid var(--border-color); color:white; border-radius:4px;">
                <input type="number" name="price" placeholder="Price ($)" required style="width:100%; padding:0.8rem; background:var(--bg-color); border:1px solid var(--border-color); color:white; border-radius:4px;">
            </div>
            <div style="margin-bottom:1rem;">
                <input type="number" name="mileage" placeholder="Mileage" required style="width:100%; padding:0.8rem; background:var(--bg-color); border:1px solid var(--border-color); color:white; border-radius:4px;">
            </div>
            <div style="display:grid; grid-template-columns: 1fr 1fr; gap:1rem; margin-bottom:1.5rem;">
                <select name="transmission" style="width:100%; padding:0.8rem; background:var(--bg-color); border:1px solid var(--border-color); color:white; border-radius:4px;">
                    <option value="Automatic">Automatic</option>
                    <option value="Manual">Manual</option>
                </select>
                <select name="fuel_type" style="width:100%; padding:0.8rem; background:var(--bg-color); border:1px solid var(--border-color); color:white; border-radius:4px;">
                    <option value="Petrol">Petrol</option>
                    <option value="Diesel">Diesel</option>
                    <option value="Electric">Electric</option>
                    <option value="Hybrid">Hybrid</option>
                </select>
            </div>
            <div style="display:grid; grid-template-columns: 1fr 1fr; gap:1rem; margin-bottom:1rem;">
                <select name="branch_id" required style="width:100%; padding:0.8rem; background:var(--bg-color); border:1px solid var(--border-color); color:white; border-radius:4px;">
                    <option value="">Select Branch</option>
                    <?php foreach ($branches as $branch): ?>
                        <option value="<?php echo $branch['id']; ?>"><?php echo htmlspecialchars($branch['name']); ?></option>
                    <?php endforeach; ?>
                </select>
                <select name="dealer_id" style="width:100%; padding:0.8rem; background:var(--bg-color); border:1px solid var(--border-color); color:white; border-radius:4px;">
                    <option value="">Select Dealer (Optional)</option>
                    <?php foreach ($dealers as $dealer): ?>
                        <option value="<?php echo $dealer['id']; ?>"><?php echo htmlspecialchars($dealer['username']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div style="margin-bottom:1.5rem;">
                <label style="color:var(--text-secondary); display:flex; align-items:center;">
                    <input type="checkbox" name="installment_available" value="1" style="width:auto; margin-right:0.5rem;">
                    Available for Installment Plan
                </label>
            </div>
            <button type="submit" name="add_car" style="width:100%; padding:0.8rem; background:var(--accent-color); border:none; border-radius:4px; color:var(--bg-color); font-weight:bold; cursor:pointer;">Add Car</button>
            <button type="button" onclick="document.getElementById('addCarModal').style.display='none'" style="width:100%; padding:0.8rem; margin-top:0.5rem; background:transparent; border:1px solid var(--border-color); color:var(--text-secondary); cursor:pointer; border-radius:4px;">Cancel</button>
        </form>
    </div>
</div>

<script>
    // Simple script to handle modal visibility since inline style display:none might be overridden by flex in CSS if I used flex
    // Actually the inline style 'display:none' on the wrapper div is correct.
    // I'll add a script to ensure it works.
    const modal = document.getElementById('addCarModal');
    
    // Auto-open if action=add
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('action') === 'add') {
        modal.style.display = 'flex';
    } else {
        // Ensure it's hidden on load if not requested
        modal.style.display = 'none';
    }
    
    // Override the button to show it as flex for centering
    document.querySelector('.page-header button').onclick = function() {
        modal.style.display = 'flex';
    };
    
    // Close on cancel
    document.querySelector('#addCarModal button[type="button"]').onclick = function() {
        modal.style.display = 'none';
    };
</script>

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