<?php
class UserDoc {

    // database connection
    private $conn;
    
    public $document;
    public $coachID;
    public $docType;
    public $docName;
    
    // constructor with $db as database connection
    public function __construct($db){
        $this->conn = $db;
    }
    
    public function getConnection() {
        return $this->conn;
    }

    function uploadUserDoc() {
        
        if (!isset($this->document['name']) || !isset($this->document['tmp_name'])) {
            return false; // Invalid file upload data
        }
        
        // Generate a random filename
        $randomFilename = $this->generateRandomFilename() . '.' . pathinfo($this->document['name'], PATHINFO_EXTENSION);
        
        // Define the path for the upload
        $upload_dir = 'userDocs/';
        $upload_file = $upload_dir . $randomFilename;
        
        
        // Move the uploaded file to the desired location
        if (move_uploaded_file($this->document['tmp_name'], $upload_file)) {
            
            $query = "INSERT INTO coachDocs (coachID, docType, docName, doc) VALUES (?,?,?,?)";
            
            // Prepare query statement
            $stmt = $this->conn->prepare($query);
            if ($stmt === false) {
                return false; // Prepare failed
            }
            
            // Sanitize
            $this->coachID = htmlspecialchars(strip_tags($this->coachID));
            $randomFilename = htmlspecialchars(strip_tags($randomFilename));
            
            // Bind new values
            $stmt->bind_param('isss', $this->coachID, $this->docType, $this->docName, $randomFilename);
            
            // Execute the query
            if ($stmt->execute()) {
                return $randomFilename;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
    
    function generateRandomFilename($length = 128) {
        return bin2hex(random_bytes($length / 2));
    }
    
}

?>