<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

//include("../config/theconfig.php");
include("header.php");

$msg = 0;
$error_msg = '';

// Check if user is logged in
if (!isset($_SESSION['customerid'])) {
    header('Location: login.php?error=nologin');
    exit();
}

$dts = date("Y-m-d H:i:s");
$customerid = $_SESSION['customerid'];

// Update last login
$stmt_lastlogin = $con->prepare("UPDATE customers SET lastlogin=? WHERE customerid=?");
$stmt_lastlogin->bind_param("si", $dts, $customerid);
$stmt_lastlogin->execute();

// Fetch customer record (so we know old image if it exists)
$stmt_customer = $con->prepare("SELECT * FROM customers WHERE customerid=?");
$stmt_customer->bind_param("i", $customerid);
$stmt_customer->execute();
$result_customer = $stmt_customer->get_result();
$rowrec = $result_customer->fetch_assoc();

// Handle profile image upload
if (isset($_POST['uploadbtn'])) {
    $file = $_FILES['product_img1'] ?? null;

    if ($file && $file['error'] === UPLOAD_ERR_OK) {
        $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        $max_size = 2 * 1024 * 1024; // 2MB

        $file_ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $new_filename = uniqid('profile_') . '.' . $file_ext;
        $upload_path = "assets/images/users/" . $new_filename;

        // Validate
        if (!in_array($file['type'], $allowed_types)) {
            $error_msg = "Only JPG, PNG, GIF, WebP allowed.";
        } elseif ($file['size'] > $max_size) {
            $error_msg = "File too large. Max 2MB.";
        } elseif (!move_uploaded_file($file['tmp_name'], $upload_path)) {
            $error_msg = "Upload failed. Check folder permissions.";
        } else {
            // Delete old image if it exists
            if (!empty($rowrec['image']) && file_exists("assets/images/users/" . $rowrec['image'])) {
                unlink("assets/images/users/" . $rowrec['image']);
            }

            // Update DB with new image
            $stmt = $con->prepare("UPDATE customers SET image=? WHERE customerid=?");
            $stmt->bind_param("si", $new_filename, $customerid);
            $stmt->execute();

            $msg = 1;
            echo "<script>setTimeout(function(){ window.location.href = 'dashboard.php'; }, 2000);</script>";
        }
    } else {
        $error_msg = "Please select an image.";
    }
}
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Profile Image Upload - <?php echo $sbank ?></title>
	<?php if (!empty($favicon)): ?>
      <link rel="icon" href="../<?= htmlspecialchars($favicon); ?>" type="image/<?= pathinfo($favicon, PATHINFO_EXTENSION); ?>">
      <?php endif; ?>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .modern-upload-container { max-width: 600px; margin: 0 auto; padding: 2rem; }
        .upload-area { border: 2px dashed #e0e6ed; border-radius: 12px; padding: 3rem 2rem; text-align: center; transition: all 0.3s ease; background: linear-gradient(145deg, #f8f9fa, #ffffff); position: relative; overflow: hidden; }
        .upload-area:hover { border-color: #4f46e5; background: linear-gradient(145deg, #f0f7ff, #ffffff); transform: translateY(-2px); box-shadow: 0 10px 30px rgba(79, 70, 229, 0.1); }
        .upload-area.dragover { border-color: #4f46e5; background: linear-gradient(145deg, #f0f7ff, #ffffff); animation: pulse 1s infinite; }
        @keyframes pulse { 0% { transform: scale(1); } 50% { transform: scale(1.02); } 100% { transform: scale(1); } }
        .upload-icon { font-size: 4rem; color: #4f46e5; margin-bottom: 1rem; transition: all 0.3s ease; }
        .upload-area:hover .upload-icon { transform: scale(1.1); color: #4f46e5; }
        .upload-text { font-size: 1.2rem; color: #495057; margin-bottom: 0.5rem; font-weight: 500; }
        .upload-subtext { color: #6c757d; font-size: 0.9rem; margin-bottom: 1.5rem; }
        .file-input { position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity: 0; cursor: pointer; }
        .upload-btn { font-size: 16px; background: linear-gradient(135deg, #4f46e5, #4338ca); border: none; color: white; padding: 0.75rem 2rem; border-radius: 5px; font-weight: 500; transition: all 0.3s ease; cursor: pointer; box-shadow: 0 5px 15px rgba(79, 70, 229, 0.3); }
        .upload-btn:hover { transform: translateY(-2px); box-shadow: 0 8px 25px rgba(79, 70, 229, 0.4); background: linear-gradient(135deg, #4338ca, #4f46e5); }
        .upload-btn:disabled { opacity: 0.6; cursor: not-allowed; transform: none; }
        .preview-container { margin-top: 2rem; text-align: center; }
        .preview-image { max-width: 200px; max-height: 200px; border-radius: 12px; box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1); margin-bottom: 1rem; }
        .file-info { background: #f8f9fa; border-radius: 8px; padding: 1rem; margin-top: 1rem; display: none; }
        .file-info.show { display: block; animation: slideDown 0.3s ease; }
        @keyframes slideDown { from { opacity: 0; transform: translateY(-10px); } to { opacity: 1; transform: translateY(0); } }
        .progress-bar { width: 100%; height: 4px; background-color: #e9ecef; border-radius: 2px; overflow: hidden; margin-top: 1rem; display: none; }
        .progress-fill { height: 100%; background: linear-gradient(90deg, #4f46e5, #4338ca); border-radius: 2px; transition: width 0.3s ease; width: 0%; }
        
        
        @media (max-width: 768px) { .modern-upload-container { padding: 1rem; } .upload-area { padding: 2rem 1rem; } .upload-icon { font-size: 3rem; } .upload-text { font-size: 1.1rem; } }
    </style>
</head>
<body data-sidebar="colored">
    <div id="layout-wrapper">
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0 font-size-18">Profile Image</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="javascript: void(0);">Dashboard</a></li>
                                        <li class="breadcrumb-item active">Upload Image</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-xl-12">
                            <div class="card">
                                <div class="card-body">
                                    <div class="modern-upload-container">
                                        <h5 class="card-title text-center mb-4">Update Your Profile Image</h5>
                                        
                                        <?php if ($msg == 1): ?>
                                            <div class="alert alert-success">
                                                <i class="fas fa-check-circle me-2"></i>
                                                Profile Image Uploaded Successfully! Redirecting...
                                            </div>
                                        <?php endif; ?>
                                        
                                        <?php if (!empty($error_msg)): ?>
                                            <div class="alert alert-danger">
                                                <i class="fas fa-exclamation-circle me-2"></i>
                                                <?php echo htmlspecialchars($error_msg); ?>
                                            </div>
                                        <?php endif; ?>

                                        <form method="POST" action="" enctype="multipart/form-data" id="uploadForm">
                                            <div class="upload-area" id="uploadArea">
                                                <div class="upload-icon">
                                                    <i class="fas fa-cloud-upload-alt"></i>
                                                </div>
                                                <div class="upload-text">Drag & Drop your image here</div>
                                                <div class="upload-subtext">or click to browse (JPG, PNG, GIF, WebP - Max 5MB)</div>
                                                <input type="file" name="product_img1" id="product_img1" class="file-input" accept="image/*" required>
                                                
                                            </div>
                                            
                                            <div class="progress-bar" id="progressBar">
                                                <div class="progress-fill" id="progressFill"></div>
                                            </div>
                                            
                                            <div class="file-info" id="fileInfo">
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <div>
                                                        <strong id="fileName"></strong>
                                                        <div class="text-muted small" id="fileSize"></div>
                                                    </div>
                                                    <button type="button" class="btn btn-sm btn-outline-danger" id="removeFile">
                                                        <i class="fas fa-times"></i>
                                                    </button>
                                                </div>
                                            </div>
                                            
                                            <div class="preview-container" id="previewContainer"></div>
                                            
                                            <div class="text-center mt-4">
                                                <button type="submit" name="uploadbtn" id="uploadbtn" class="upload-btn" disabled>
                                                   <svg width="25" height="25" viewBox="0 0 25 24" fill="none" xmlns="http://www.w3.org/2000/svg" transform="rotate(0 0 0)">
<path opacity="0.4" d="M5.17188 16C5.17188 15.5858 4.83609 15.25 4.42188 15.25C4.00766 15.25 3.67188 15.5858 3.67188 16V18.5C3.67188 19.7426 4.67923 20.75 5.92188 20.75H18.9227C20.1654 20.75 21.1727 19.7426 21.1727 18.5V16C21.1727 15.5858 20.837 15.25 20.4227 15.25C20.0085 15.25 19.6727 15.5858 19.6727 16V18.5C19.6727 18.9142 19.337 19.25 18.9227 19.25H5.92188C5.50766 19.25 5.17188 18.9142 5.17188 18.5V16Z" fill="#ffffff"/>
<path d="M12.4238 3.25C12.2078 3.25 12.0132 3.34131 11.8763 3.48744L7.26671 8.0941C6.97373 8.3869 6.97358 8.86177 7.26638 9.15476C7.55918 9.44775 8.03405 9.4479 8.32704 9.1551L11.6738 5.81043L11.6738 16C11.6738 16.4142 12.0096 16.75 12.4238 16.75C12.838 16.75 13.1738 16.4142 13.1738 16L13.1738 5.81455L16.5167 9.15511C16.8097 9.4479 17.2846 9.44774 17.5774 9.15474C17.8702 8.86175 17.87 8.38687 17.577 8.09408L13.0021 3.52236C12.8645 3.356 12.6566 3.25 12.4238 3.25Z" fill="#ffffff"/>
</svg>
Upload Image
                                                </button>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <?php include 'footer.php' ?>
        </div>
    </div>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
    const uploadArea = document.getElementById('uploadArea');
    const fileInput = document.getElementById('product_img1');
    const uploadBtn = document.getElementById('uploadbtn');
    const fileInfo = document.getElementById('fileInfo');
    const fileNameDisplay = document.getElementById('fileName');
    const fileSizeDisplay = document.getElementById('fileSize');
    const removeFileBtn = document.getElementById('removeFile');
    const previewContainer = document.getElementById('previewContainer');

    // Drag and drop events
    ['dragenter', 'dragover'].forEach(eventName => {
        uploadArea.addEventListener(eventName, e => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });
    });

    ['dragleave', 'drop'].forEach(eventName => {
        uploadArea.addEventListener(eventName, e => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
        });
    });

    uploadArea.addEventListener('drop', e => {
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            fileInput.files = files;
            handleFileSelect(files[0]);
        }
    });

    // Handle file selection from input
    fileInput.addEventListener('change', e => {
        if (e.target.files.length > 0) {
            handleFileSelect(e.target.files[0]);
        }
    });

    // Handle file removal
    removeFileBtn.addEventListener('click', () => {
        fileInput.value = ''; // Clear the input
        fileInfo.classList.remove('show');
        previewContainer.innerHTML = '';
        uploadBtn.disabled = true;
    });

    function handleFileSelect(file) {
        const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        const maxSizeInBytes = 2 * 1024 * 1024; // 2MB from PHP code

        // Client-side validation
        if (!allowedTypes.includes(file.type)) {
            alert('Invalid file type. Only JPG, PNG, GIF, and WebP are allowed.');
            fileInput.value = '';
            uploadBtn.disabled = true;
            return;
        }

        if (file.size > maxSizeInBytes) {
            alert('File size is too large. Max 2MB allowed.');
            fileInput.value = '';
            uploadBtn.disabled = true;
            return;
        }

        // All good, update UI
        fileNameDisplay.textContent = file.name;
        fileSizeDisplay.textContent = formatFileSize(file.size);
        fileInfo.classList.add('show');
        uploadBtn.disabled = false;

        // Display image preview
        const reader = new FileReader();
        reader.onload = e => {
            previewContainer.innerHTML = `<img src="${e.target.result}" class="preview-image" alt="Preview">`;
        };
        reader.readAsDataURL(file);
    }

    // Helper function for file size
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
});
    </script>

    <script src="assets/libs/jquery/jquery.min.js"></script>
    <script src="assets/libs/simplebar/simplebar.min.js"></script>
    <script src="assets/libs/node-waves/waves.min.js"></script>
    <script src="assets/libs/apexcharts/apexcharts.min.js"></script>
    <script src="assets/js/pages/dashboard.init.js"></script>
    <script src="assets/js/app.js"></script>
    <script src="assets/libs2/node_modules/datatables.net/js/jquery.dataTables.js"></script>
    <script src="assets/node_modules/libs2/datatables.net-bs4/js/dataTables.bootstrap4.js"></script>
    <script src="assets/libs2/custom/data-table.js"></script>
</body>
</html>