<?php 
include "../../includes/db.php";
include "../../includes/auth.php";

$id = (int)$_GET['id'];
$certType = $_GET['type'] ?? 'real';
$certType = $certType === 'automotive' ? 'automotive' : 'real';
$tableName = $certType === 'automotive' ? 'automotive_certifications' : 'certifications';

$cert = $conn->query("SELECT * FROM $tableName WHERE id=$id")->fetch_assoc();

if (!$cert) {
    header("Location: certification.php");
    exit;
}

if ($_POST) {
    $title = mysqli_real_escape_string($conn, $_POST['title']);
    $hasImage = false;
    $imageCol = $conn->query("SHOW COLUMNS FROM $tableName LIKE 'image'");
    if ($imageCol && $imageCol->num_rows > 0) {
        $hasImage = true;
    } else {
        $conn->query("ALTER TABLE $tableName ADD COLUMN image VARCHAR(255) NULL AFTER title");
        $imageCol = $conn->query("SHOW COLUMNS FROM $tableName LIKE 'image'");
        if ($imageCol && $imageCol->num_rows > 0) {
            $hasImage = true;
        }
    }

    $imageRel = $cert['image'] ?? '';
    if (!empty($imageRel)) {
        $imageRel = basename(str_replace(['../', '..\\'], '', $imageRel));
    }
    if (!empty($_FILES['image']['name'] ?? '')) {
        $target_dir = "../../../files/";
        if (!is_dir($target_dir)) {
            mkdir($target_dir, 0755, true);
        }
        $fileName = time() . "_" . basename($_FILES["image"]["name"]);
        $target_file = $target_dir . $fileName;
        move_uploaded_file($_FILES["image"]["tmp_name"], $target_file);
        $imageRel = $fileName;
    }

    $setParts = [
        "title='$title'"
    ];
    if ($hasImage) {
        $setParts[] = "image='$imageRel'";
    }

    $setSql = implode(", ", $setParts);
    $conn->query("UPDATE $tableName SET $setSql WHERE id=$id");
    header("Location: certification.php");
    exit;
}

include "../../includes/header.php"; 
include "../../includes/sidebar.php"; 
?>

<style>
.form-container {
    max-width: 700px;
    margin: 0 auto;
}

.form-card {
    background: white;
    border-radius: 12px;
    padding: 30px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}

.form-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    padding-bottom: 15px;
    border-bottom: 2px solid #f0f0f0;
}

.page-title {
    color: #0f2a44;
    font-weight: 600;
    font-size: 24px;
    margin: 0;
}

.form-group {
    margin-bottom: 20px;
}

.form-label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
    color: #333;
    font-size: 14px;
}

.form-control {
    width: 100%;
    padding: 10px 15px;
    border: 1px solid #ddd;
    border-radius: 6px;
    font-size: 14px;
    transition: 0.3s;
}

.form-control:focus {
    outline: none;
    border-color: #667eea;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.btn-group {
    display: flex;
    gap: 10px;
    margin-top: 30px;
    padding-top: 15px;
    border-top: 1px solid #f0f0f0;
}

.btn-submit {
    background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 10px 30px;
    border: none;
    border-radius: 6px;
    font-weight: 500;
    cursor: pointer;
    transition: 0.3s;
}

.btn-submit:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3);
}

.btn-cancel {
    background: #f0f0f0;
    color: #333;
    padding: 10px 30px;
    border: none;
    border-radius: 6px;
    font-weight: 500;
    cursor: pointer;
    transition: 0.3s;
    text-decoration: none;
    display: inline-block;
}

.btn-cancel:hover {
    background: #e0e0e0;
}

.current-image {
    display: flex;
    gap: 15px;
    align-items: center;
    margin-bottom: 15px;
    padding: 15px;
    background: #f9f9f9;
    border-radius: 6px;
}

.current-image img {
    width: 80px;
    height: 80px;
    object-fit: cover;
    border-radius: 6px;
}

.file-input-wrapper {
    position: relative;
    overflow: hidden;
    display: inline-block;
    width: 100%;
}

.file-input-wrapper input[type=file] {
    position: absolute;
    left: -9999px;
}

.file-input-label {
    display: block;
    padding: 20px;
    background: #f9f9f9;
    border: 2px dashed #ddd;
    border-radius: 6px;
    text-align: center;
    cursor: pointer;
    transition: 0.3s;
}

.file-input-label:hover {
    background: #f0f0f0;
    border-color: #667eea;
}
</style>


<div class="container-fluid">
    <div class="form-container">
        <div class="form-card">
            <div class="form-header">
                <h2 class="page-title">Edit Certification</h2>
                <a href="certification.php" class="btn btn-cancel" style="margin-bottom: 0;">← Back</a>
            </div>

            <form method="post" enctype="multipart/form-data">
                <input type="hidden" name="cert_type" value="<?= htmlspecialchars($certType) ?>">
                <div class="form-group">
                    <label class="form-label">Certificate Type *</label>
                    <input type="text" class="form-control" value="<?= $certType === 'automotive' ? 'Automotive Parts Certification' : 'Real Estate Certification' ?>" readonly>
                </div>

                <div class="form-group">
                    <label class="form-label">Certification Title *</label>
                    <input type="text" name="title" class="form-control" value="<?= htmlspecialchars($cert['title']) ?>" required>
                </div>

                <div class="form-group">
    <label class="form-label">Certificate Image</label>
    <?php
      $imagePath = $cert['image'] ?? '';
      $imagePath = basename(str_replace(['../', '..\\'], '', $imagePath));
      if (!empty($imagePath)) {
          $imagePath = "../../files/" . $imagePath;
      }
    ?>
    <?php if (!empty($imagePath)): ?>
        <div class="current-image">
            <div>
                <img src="<?= htmlspecialchars($imagePath) ?>" alt="Certificate" onerror="this.onerror=null;this.src='/firstchoice_admin/admin/files/<?= htmlspecialchars(basename($cert['image'] ?? '')) ?>';">
            </div>
            <div>
                <small style="color: #999;">Current image</small>
            </div>
        </div>
    <?php endif; ?>
                    
                    <div class="file-input-wrapper">
                        <input type="file" id="image" name="image" accept="image/*" onchange="displayFileName(this)">
                        <label for="image" class="file-input-label">
                            <i class="fas fa-cloud-upload-alt" style="font-size: 24px; color: #667eea; margin-bottom: 10px; display: block;"></i>
                            <span id="fileName">Click to upload or drag and drop</span><br>
                            <small style="color: #999;">PNG, JPG, GIF up to 10MB (leave empty to keep current)</small>
                        </label>
                    </div>
                </div>

                <div class="btn-group">
                    <button type="submit" class="btn-submit">
                        <i class="fas fa-save"></i> Update Certification
                    </button>
                    <a href="certification.php" class="btn-cancel">
                        <i class="fas fa-times"></i> Cancel
                    </a>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function displayFileName(input) {
    const fileName = input.files[0]?.name || 'Click to upload or drag and drop';
    document.getElementById('fileName').textContent = fileName;
}

// Drag and drop functionality
const fileInputLabel = document.querySelector('.file-input-label');
const fileInput = document.getElementById('image');

if (fileInputLabel) {
    fileInputLabel.addEventListener('dragover', (e) => {
        e.preventDefault();
        fileInputLabel.style.background = '#f0f0f0';
        fileInputLabel.style.borderColor = '#667eea';
    });

    fileInputLabel.addEventListener('dragleave', () => {
        fileInputLabel.style.background = '#f9f9f9';
        fileInputLabel.style.borderColor = '#ddd';
    });

    fileInputLabel.addEventListener('drop', (e) => {
        e.preventDefault();
        fileInputLabel.style.background = '#f9f9f9';
        fileInputLabel.style.borderColor = '#ddd';
        if (e.dataTransfer.files.length > 0) {
            fileInput.files = e.dataTransfer.files;
            displayFileName(fileInput);
        }
    });
}
</script>

<?php include "../../includes/footer.php"; ?>
