<?php
// admin/edit-car.php - Versioni që RUAJ emoji-t dhe krijon thumbnail
require_once '../includes/config.php';

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

$car_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if($car_id == 0) {
    header('Location: cars.php');
    exit();
}

// Get car data
$stmt = $pdo->prepare("SELECT * FROM cars WHERE id = ?");
$stmt->execute([$car_id]);
$car = $stmt->fetch(PDO::FETCH_ASSOC);

if(!$car) {
    header('Location: cars.php');
    exit();
}

$message = '';
$error = '';

// Function to compress and resize image
function compressImage($source_path, $destination_path, $max_width = 1200, $max_height = 800, $quality = 85) {
    if(!extension_loaded('gd')) {
        return false;
    }
    
    $image_info = @getimagesize($source_path);
    if (!$image_info) return false;
    
    $mime = $image_info['mime'];
    $original_width = $image_info[0];
    $original_height = $image_info[1];
    
    $ratio = min($max_width / $original_width, $max_height / $original_height, 1);
    $new_width = round($original_width * $ratio);
    $new_height = round($original_height * $ratio);
    
    switch($mime) {
        case 'image/jpeg':
        case 'image/jpg':
            $source = @imagecreatefromjpeg($source_path);
            break;
        case 'image/png':
            $source = @imagecreatefrompng($source_path);
            break;
        case 'image/gif':
            $source = @imagecreatefromgif($source_path);
            break;
        case 'image/webp':
            if(function_exists('imagecreatefromwebp')) {
                $source = @imagecreatefromwebp($source_path);
            } else {
                return false;
            }
            break;
        default:
            return false;
    }
    
    if(!$source) return false;
    
    $destination = imagecreatetruecolor($new_width, $new_height);
    
    if($mime == 'image/png') {
        imagealphablending($destination, false);
        imagesavealpha($destination, true);
        $transparent = imagecolorallocatealpha($destination, 255, 255, 255, 127);
        imagefilledrectangle($destination, 0, 0, $new_width, $new_height, $transparent);
    }
    
    imagecopyresampled($destination, $source, 0, 0, 0, 0, $new_width, $new_height, $original_width, $original_height);
    
    switch($mime) {
        case 'image/jpeg':
        case 'image/jpg':
            $result = imagejpeg($destination, $destination_path, $quality);
            break;
        case 'image/png':
            $png_quality = round(9 - ($quality / 100) * 9);
            $result = imagepng($destination, $destination_path, $png_quality);
            break;
        case 'image/gif':
            $result = imagegif($destination, $destination_path);
            break;
        case 'image/webp':
            if(function_exists('imagewebp')) {
                $result = imagewebp($destination, $destination_path, $quality);
            } else {
                $result = false;
            }
            break;
        default:
            $result = false;
    }
    
    imagedestroy($source);
    imagedestroy($destination);
    
    return $result;
}

// Handle form submission
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_car'])) {
    try {
        $brand = trim($_POST['brand'] ?? '');
        $model = trim($_POST['model'] ?? '');
        $license_plate = trim($_POST['license_plate'] ?? '');
        $car_type = $_POST['car_type'] ?? 'economy';
        $year = (int)($_POST['year'] ?? date('Y'));
        $fuel_type = $_POST['fuel_type'] ?? 'Benzine';
        $transmission = $_POST['transmission'] ?? 'Manual';
        $seats = (int)($_POST['seats'] ?? 5);
        $luggage = (int)($_POST['luggage'] ?? 2);
        $description = trim($_POST['description'] ?? '');
        $key_features = trim($_POST['key_features'] ?? '');
        $status = $_POST['status'] ?? 'available';
        $image_url = $_POST['existing_image'] ?? '';
        
        $errors = [];
        
        if(empty($brand)) $errors[] = "Brand is required";
        if(empty($model)) $errors[] = "Model is required";
        if(empty($license_plate)) $errors[] = "License plate is required";
        
        // Check if license plate already exists for another car
        $stmt = $pdo->prepare("SELECT id FROM cars WHERE license_plate = ? AND id != ?");
        $stmt->execute([$license_plate, $car_id]);
        if($stmt->fetch()) {
            $errors[] = "License plate already exists for another car!";
        }
        
        // Handle image upload
        if(isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
            if($_FILES['image']['size'] > 10485760) {
                $errors[] = "Image too large! Maximum size is 10MB.";
            } else {
                $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
                $filename = $_FILES['image']['name'];
                $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
                
                if(in_array($ext, $allowed)) {
                    $new_filename = time() . '_' . uniqid() . '.' . $ext;
                    $temp_path = $_FILES['image']['tmp_name'];
                    $upload_dir = '../uploads/';
                    $thumb_dir = '../uploads/thumbnails/';
                    
                    // Ensure directories exist
                    if(!file_exists($upload_dir)) {
                        mkdir($upload_dir, 0777, true);
                    }
                    if(!file_exists($thumb_dir)) {
                        mkdir($thumb_dir, 0777, true);
                    }
                    
                    $destination = $upload_dir . $new_filename;
                    $thumb_destination = $thumb_dir . $new_filename;
                    
                    // Delete old images if exist
                    if($image_url) {
                        deleteCarImages($image_url);
                    }
                    
                    // Compress and save original
                    if(compressImage($temp_path, $destination, 1200, 800, 85)) {
                        $image_url = 'uploads/' . $new_filename;
                        // Create thumbnail
                        createThumbnail($destination, $thumb_destination, 150, 150);
                    } else {
                        if(move_uploaded_file($temp_path, $destination)) {
                            $image_url = 'uploads/' . $new_filename;
                            // Create thumbnail
                            createThumbnail($destination, $thumb_destination, 150, 150);
                        } else {
                            $errors[] = "Error uploading image!";
                        }
                    }
                } else {
                    $errors[] = "Invalid image format! Use JPG, PNG, GIF, or WEBP.";
                }
            }
        }
        
        if(empty($errors)) {
            $sql = "UPDATE cars SET brand=?, model=?, license_plate=?, car_type=?, year=?, fuel_type=?, transmission=?, 
                    seats=?, luggage=?, description=?, key_features=?, image_url=?, status=? WHERE id=?";
            $stmt = $pdo->prepare($sql);
            
            if($stmt->execute([$brand, $model, $license_plate, $car_type, $year, $fuel_type, $transmission, 
                              $seats, $luggage, $description, $key_features, $image_url, $status, $car_id])) {
                $message = "Car updated successfully!";
                // Refresh car data
                $stmt = $pdo->prepare("SELECT * FROM cars WHERE id = ?");
                $stmt->execute([$car_id]);
                $car = $stmt->fetch(PDO::FETCH_ASSOC);
            } else {
                $error = "Error updating car!";
            }
        } else {
            $error = implode("<br>", $errors);
        }
        
    } catch (Exception $e) {
        $error = "System error: " . $e->getMessage();
    }
}

$type_labels = [
    'economy' => 'Economy',
    'sedan' => 'Sedan',
    'suv' => 'SUV',
    '7-seats' => '7+ Seats',
    'cabrio' => 'Cabrio',
    'luxury' => 'Luxury'
];

$page_title = 'Edit Car - ' . $car['brand'] . ' ' . $car['model'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?> - Admin</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; }
        
        .sidebar {
            width: 260px;
            background: #1a1a2e;
            color: white;
            position: fixed;
            left: 0;
            top: 0;
            bottom: 0;
            overflow-y: auto;
            z-index: 100;
        }
        .sidebar-header { padding: 24px 20px; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .sidebar-header h2 { font-size: 18px; font-weight: 600; }
        .sidebar-nav { padding: 20px 0; }
        .sidebar-nav a {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 20px;
            color: #cbd5e1;
            text-decoration: none;
            font-size: 14px;
            transition: all 0.2s;
        }
        .sidebar-nav a i { width: 20px; }
        .sidebar-nav a:hover, .sidebar-nav a.active { background: #0066cc; color: white; }
        
        .main-content { margin-left: 260px; padding: 24px; }
        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24px;
            flex-wrap: wrap;
            gap: 16px;
        }
        .page-header h1 { font-size: 24px; font-weight: 600; }
        .page-header h1 i { color: #0066cc; margin-right: 10px; }
        
        .btn-back {
            background: #6b7280;
            color: white;
            padding: 10px 20px;
            border-radius: 8px;
            text-decoration: none;
            font-size: 14px;
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        .btn-back:hover { background: #4b5563; }
        
        .btn-price {
            background: #10b981;
            color: white;
            padding: 10px 20px;
            border-radius: 8px;
            text-decoration: none;
            font-size: 14px;
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        .btn-price:hover { background: #059669; }
        
        .form-card {
            background: white;
            border-radius: 12px;
            border: 1px solid #e5e7eb;
            padding: 28px;
            max-width: 900px;
        }
        
        .alert-success {
            background: #d1fae5;
            color: #065f46;
            padding: 14px 18px;
            border-radius: 10px;
            margin-bottom: 24px;
            border-left: 4px solid #10b981;
        }
        .alert-error {
            background: #fee2e2;
            color: #991b1b;
            padding: 14px 18px;
            border-radius: 10px;
            margin-bottom: 24px;
            border-left: 4px solid #dc2626;
        }
        
        .form-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
        }
        .form-group { margin-bottom: 16px; }
        .form-group.full-width { grid-column: span 2; }
        .form-group label {
            display: block;
            margin-bottom: 6px;
            font-weight: 500;
            font-size: 13px;
            color: #374151;
        }
        .form-group label .required { color: #dc2626; }
        .form-group input, .form-group select, .form-group textarea {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            font-size: 14px;
            font-family: inherit;
        }
        .form-group textarea { resize: vertical; min-height: 100px; }
        .help-text { font-size: 11px; color: #6b7280; margin-top: 4px; }
        
        .current-image {
            margin-top: 8px;
            max-width: 150px;
        }
        .current-image img {
            width: 100%;
            border-radius: 8px;
            border: 1px solid #e5e7eb;
        }
        .image-preview {
            margin-top: 12px;
            max-width: 200px;
            display: none;
        }
        .image-preview img {
            width: 100%;
            border-radius: 8px;
            border: 1px solid #e5e7eb;
        }
        
        .btn-submit {
            background: #10b981;
            color: white;
            padding: 12px 28px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            margin-top: 16px;
            transition: background 0.2s;
        }
        .btn-submit:hover { background: #059669; }
        
        .emoji-info {
            background: #fef3c7;
            padding: 8px 12px;
            border-radius: 8px;
            margin-top: 8px;
            font-size: 12px;
            color: #92400e;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        @media (max-width: 768px) {
            .sidebar { width: 100%; position: relative; height: auto; }
            .main-content { margin-left: 0; }
            .form-grid { grid-template-columns: 1fr; }
            .form-group.full-width { grid-column: span 1; }
        }
    </style>
</head>
<body>
    <div class="sidebar">
        <div class="sidebar-header"><h2><i class="fas fa-car"></i> Car Rental Admin</h2></div>
        <div class="sidebar-nav">
            <a href="dashboard.php"><i class="fas fa-tachometer-alt"></i> Dashboard</a>
            <a href="cars.php" class="active"><i class="fas fa-car"></i> Cars</a>
            <a href="create-reservation.php"><i class="fas fa-plus-square"></i> Create Reservation</a>
            <a href="reservations.php"><i class="fas fa-calendar-check"></i> Reservations</a>
            <a href="calendar.php"><i class="fas fa-calendar-alt"></i> Calendar</a>
            <a href="price-list.php"><i class="fas fa-tags"></i> Price Rules</a>
            <a href="settings.php"><i class="fas fa-cog"></i> Settings</a>
            <a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </div>
    </div>
    
    <div class="main-content">
        <div class="page-header">
            <h1><i class="fas fa-edit"></i> Edit Car: <?php echo htmlspecialchars($car['brand'] . ' ' . $car['model'], ENT_QUOTES, 'UTF-8'); ?></h1>
            <div style="display: flex; gap: 12px;">
                <a href="price-list.php?car_id=<?php echo $car['id']; ?>" class="btn-price"><i class="fas fa-tags"></i> Manage Price Rules</a>
                <a href="cars.php" class="btn-back"><i class="fas fa-arrow-left"></i> Back to Cars</a>
            </div>
        </div>
        
        <?php if($message): ?>
            <div class="alert-success"><i class="fas fa-check-circle"></i> <?php echo $message; ?></div>
        <?php endif; ?>
        
        <?php if($error): ?>
            <div class="alert-error"><i class="fas fa-exclamation-circle"></i> <?php echo $error; ?></div>
        <?php endif; ?>
        
        <div class="form-card">
            <form method="POST" enctype="multipart/form-data" accept-charset="UTF-8">
                <input type="hidden" name="update_car" value="1">
                <input type="hidden" name="existing_image" value="<?php echo htmlspecialchars($car['image_url'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                
                <div class="form-grid">
                    <div class="form-group">
                        <label>Brand <span class="required">*</span></label>
                        <input type="text" name="brand" value="<?php echo htmlspecialchars($car['brand'], ENT_QUOTES, 'UTF-8'); ?>" required>
                    </div>
                    <div class="form-group">
                        <label>Model <span class="required">*</span></label>
                        <input type="text" name="model" value="<?php echo htmlspecialchars($car['model'], ENT_QUOTES, 'UTF-8'); ?>" required>
                    </div>
                </div>
                
                <div class="form-grid">
                    <div class="form-group">
                        <label>License Plate <span class="required">*</span></label>
                        <input type="text" name="license_plate" value="<?php echo htmlspecialchars($car['license_plate'], ENT_QUOTES, 'UTF-8'); ?>" required>
                        <div class="help-text">Unique vehicle registration number</div>
                    </div>
                    <div class="form-group">
                        <label>Car Type</label>
                        <select name="car_type">
                            <?php foreach($type_labels as $key => $label): ?>
                                <option value="<?php echo $key; ?>" <?php echo $car['car_type'] == $key ? 'selected' : ''; ?>><?php echo $label; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                
                <div class="form-grid">
                    <div class="form-group">
                        <label>Year</label>
                        <input type="number" name="year" min="1990" max="2026" value="<?php echo $car['year']; ?>">
                    </div>
                    <div class="form-group">
                        <label>Fuel Type</label>
                        <select name="fuel_type">
                            <option value="Benzine" <?php echo $car['fuel_type'] == 'Benzine' ? 'selected' : ''; ?>>Petrol</option>
                            <option value="Diesel" <?php echo $car['fuel_type'] == 'Diesel' ? 'selected' : ''; ?>>Diesel</option>
                            <option value="Elektrik" <?php echo $car['fuel_type'] == 'Elektrik' ? 'selected' : ''; ?>>Electric</option>
                            <option value="Hibrid" <?php echo $car['fuel_type'] == 'Hibrid' ? 'selected' : ''; ?>>Hybrid</option>
                        </select>
                    </div>
                </div>
                
                <div class="form-grid">
                    <div class="form-group">
                        <label>Transmission</label>
                        <select name="transmission">
                            <option value="Manual" <?php echo $car['transmission'] == 'Manual' ? 'selected' : ''; ?>>Manual</option>
                            <option value="Automatic" <?php echo $car['transmission'] == 'Automatic' ? 'selected' : ''; ?>>Automatic</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Seats</label>
                        <input type="number" name="seats" min="2" max="9" value="<?php echo $car['seats']; ?>">
                    </div>
                </div>
                
                <div class="form-grid">
                    <div class="form-group">
                        <label>Luggage (bags)</label>
                        <input type="number" name="luggage" min="0" max="10" value="<?php echo $car['luggage']; ?>">
                    </div>
                    <div class="form-group">
                        <label>Status</label>
                        <select name="status">
                            <option value="available" <?php echo $car['status'] == 'available' ? 'selected' : ''; ?>>Available</option>
                            <option value="maintenance" <?php echo $car['status'] == 'maintenance' ? 'selected' : ''; ?>>Maintenance</option>
                        </select>
                    </div>
                </div>
                
                <div class="form-group full-width">
                    <label>Description</label>
                    <textarea name="description" placeholder="Describe the car... (✅ You can use emojis and any format!)" style="min-height: 120px;"><?php echo htmlspecialchars($car['description'] ?? '', ENT_QUOTES, 'UTF-8'); ?></textarea>
                    <div class="help-text">✅ Emojis and special characters are fully supported!</div>
                </div>
                
                <div class="form-group full-width">
                    <label>Key Features (one per line)</label>
                    <textarea name="key_features" placeholder="🔹 Air conditioning&#10;🔸 Bluetooth connectivity&#10;⭐ GPS navigation&#10;❤️ Heated seats&#10;🎵 Premium sound system" style="min-height: 150px;"><?php echo htmlspecialchars($car['key_features'] ?? '', ENT_QUOTES, 'UTF-8'); ?></textarea>
                    <div class="help-text">✅ One feature per line - Emojis are fully supported!</div>
                    <div class="emoji-info">
                        <i class="fas fa-smile-wink"></i>
                        <span>You can use emojis, special characters, and any text format!</span>
                    </div>
                </div>
                
                <div class="form-group full-width">
                    <label>Current Image</label>
                    <?php 
                    $thumb_exists = false;
                    if($car['image_url']) {
                        $thumb_path = str_replace('uploads/', 'uploads/thumbnails/', $car['image_url']);
                        if(file_exists('../' . $thumb_path)) {
                            $thumb_exists = true;
                            $display_image = $thumb_path;
                        } else {
                            $display_image = $car['image_url'];
                        }
                    }
                    ?>
                    <?php if($car['image_url']): ?>
                    <div class="current-image">
                        <img src="../<?php echo $display_image ?? $car['image_url']; ?>" alt="Current image">
                        <?php if($thumb_exists): ?>
                            <div class="help-text">✅ Thumbnail version shown</div>
                        <?php endif; ?>
                    </div>
                    <?php else: ?>
                    <div class="help-text">No image uploaded</div>
                    <?php endif; ?>
                    
                    <label style="margin-top: 12px;">Change Image</label>
                    <input type="file" name="image" accept="image/jpeg,image/png,image/gif,image/webp" onchange="previewImage(this)">
                    <div class="help-text">Max size: 10MB. A thumbnail (150x150) will be created automatically.</div>
                    <div class="image-preview" id="imagePreview">
                        <img id="previewImg" src="">
                    </div>
                </div>
                
                <button type="submit" class="btn-submit"><i class="fas fa-save"></i> Save Changes</button>
            </form>
        </div>
    </div>
    
    <script>
        function previewImage(input) {
            const preview = document.getElementById('imagePreview');
            const img = document.getElementById('previewImg');
            if(input.files && input.files[0]) {
                if(input.files[0].size > 10485760) {
                    alert('Image is too large! Maximum size is 10MB.');
                    input.value = '';
                    preview.style.display = 'none';
                    return;
                }
                const reader = new FileReader();
                reader.onload = function(e) {
                    img.src = e.target.result;
                    preview.style.display = 'block';
                }
                reader.readAsDataURL(input.files[0]);
            }
        }
    </script>
</body>
</html>