<?php
// Database connection (assuming $con is already established)
// $con = mysqli_connect("host", "username", "password", "database");

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['id_card_backpart_teacher'])) {
    $targetDir = "male/img/";
    
    // Create directory if it doesn't exist
    if (!file_exists($targetDir)) {
        mkdir($targetDir, 0777, true);
    }
    
    // Get file details and add timestamp to filename
    $originalFileName = basename($_FILES['id_card_backpart_teacher']['name']);
    $fileExtension = pathinfo($originalFileName, PATHINFO_EXTENSION);
    $fileNameWithoutExt = pathinfo($originalFileName, PATHINFO_FILENAME);
    
    // Add current date and time (with minutes) to filename
    $timestamp = date("Ymd_His"); // YearMonthDay_HourMinuteSecond
    $newFileName = $fileNameWithoutExt . '_' . $timestamp . '.' . $fileExtension;
    
    $targetFilePath = $targetDir . $newFileName;
    $fileType = strtolower($fileExtension);
    
    // Allow certain file formats
    $allowTypes = array('jpg', 'png', 'jpeg', 'gif');
    
    if (in_array($fileType, $allowTypes)) {
        // Check if user already has an image in database
        $checkQuery = "SELECT id_card_backpart_teacher  FROM academic WHERE academic_id=1"; // Replace [USER_ID] with actual user ID
        $checkResult = mysqli_query($con, $checkQuery);
        
        if ($checkResult && mysqli_num_rows($checkResult) > 0) {
            $row = mysqli_fetch_assoc($checkResult);
            $oldFileName = $row['id_card_backpart_teacher'];
            
            // Delete old file if it exists
            if (!empty($oldFileName)) {
                $oldFilePath = $targetDir . $oldFileName;
                if (file_exists($oldFilePath)) {
                    unlink($oldFilePath);
                }
            }
        }
        
        // Upload new file
        if (move_uploaded_file($_FILES['id_card_backpart_teacher']['tmp_name'], $targetFilePath)) {
            // Update database with only the filename (not full path)
            $updateQuery = "UPDATE academic SET id_card_backpart_teacher = '$newFileName' WHERE academic_id=1"; // Replace [USER_ID]
            
            if (mysqli_query($con, $updateQuery)) {
                $statusMsg = "The file ".$originalFileName. " has been uploaded successfully as ".$newFileName;
            } else {
                $statusMsg = "File upload failed, please try again.";
            }
        } else {
            $statusMsg = "Sorry, there was an error uploading your file.";
        }
    } else {
        $statusMsg = 'Sorry, only JPG, JPEG, PNG, & GIF files are allowed to upload.';
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Upload</title>
    <!-- Bootstrap 4 CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h4>Upload ID Card Image</h4>
                    </div>
                    <div class="card-body">
                        <?php if (!empty($statusMsg)) { ?>
                            <div class="alert alert-<?php echo strpos($statusMsg, 'successfully') !== false ? 'success' : 'danger'; ?>">
                                <?php echo $statusMsg; ?>
                            </div>
                        <?php } ?>
                        
                        <form action="" method="post" enctype="multipart/form-data">
                            <div class="form-group">
                                <label>Select Image to Upload:</label>
                                <div class="custom-file">
                                    <input type="file" class="custom-file-input" id="id_card_backpart_teacher" name="id_card_backpart_teacher" required>
                                    <label class="custom-file-label" for="id_card_backpart_teacher">Choose file</label>
                                </div>
                                <small class="form-text text-muted">
                                    Only JPG, JPEG, PNG, GIF files are allowed. Filename will include timestamp.
                                </small>
                            </div>
                            <button type="submit" name="submit" class="btn btn-primary">Upload Image</button>
                        </form>
                    </div>
                </div>
                
                <!-- Display current image if exists -->
                <?php
                $query = "SELECT id_card_backpart_teacher FROM academic WHERE academic_id=1"; // Replace [USER_ID]
                $result = mysqli_query($con, $query);
                
                if ($result && mysqli_num_rows($result) > 0) {
                    $row = mysqli_fetch_assoc($result);
                    if (!empty($row['id_card_backpart_teacher'])) {
                        $imagePath = "male/img/" . $row['id_card_backpart_teacher'];
                        if (file_exists($imagePath)) {
                            echo '<div class="card mt-3">
                                    <div class="card-header">
                                        <h5>Current Image</h5>
                                    </div>
                                    <div class="card-body text-center">
                                        <img src="'.$imagePath.'" class="img-fluid" style="max-height: 300px;">
                                    </div>
                                  </div>';
                        }
                    }
                }
                ?>
            </div>
        </div>
    </div>
    
    <!-- Bootstrap 4 JS and dependencies -->
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    
    <script>
        // Show file name in file input
        $('.custom-file-input').on('change', function() {
            let fileName = $(this).val().split('\\').pop();
            $(this).next('.custom-file-label').addClass("selected").html(fileName);
        });
    </script>
</body>
</html>