<?php

// Enable error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Configuration
$dropbox_url = 'https://www.dropbox.com/scl/fi/bdh00cy7xwramn37kbvup/spareparts.xlsx?rlkey=x7vpgp6g53mubfjzu8nsh6ai2&dl=1';
$local_path = __DIR__ . '/spareparts.xlsx'; // Filename to save in the same directory as the script
$email_host = 'smtp.labotek.dk';
$email_port = 587;
$email_user = 'moi@labotek.dk';
$config = include('config.php'); // Assuming config.php is in the same directory
$email_pass = $config['email_pass'];
$to_email = 'moi@labotek.dk';
$log_file = 'update_log.txt'; // Log file in the same directory

// Log message to file
function log_message($message) {
    global $log_file;
    file_put_contents($log_file, date('Y-m-d H:i:s') . " - " . $message . PHP_EOL, FILE_APPEND);
}

// Verify the integrity of the downloaded file
function verify_file($file_path) {
    if (file_exists($file_path) && filesize($file_path) > 0) {
        return true;
    }
    return false;
}

// Download file with cURL and retry mechanism
function download_file($url, $local_path, $retries = 3) {
    $attempts = 0;
    while ($attempts < $retries) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_HEADER, true); // Enable header
        curl_setopt($ch, CURLOPT_VERBOSE, true); // Enable verbose output
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        
        $file_content = curl_exec($ch);
        $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $headers = substr($file_content, 0, $header_size);
        $body = substr($file_content, $header_size);
        
        curl_close($ch);

        // Log response for debugging
        log_message("Response headers: " . $headers);
        log_message("Response body: " . substr($body, 0, 200)); // Log first 200 characters

        if ($http_status == 200 && $body !== false) {
            file_put_contents($local_path, $body);
            if (verify_file($local_path)) {
                log_message("File successfully saved to $local_path.");
                return true;
            } else {
                log_message("Downloaded file is corrupt or empty.");
            }
        } else {
            $attempts++;
            log_message("Attempt $attempts failed: HTTP Status: $http_status. cURL Error: $error.");
            if ($attempts >= $retries) {
                return "HTTP Status: $http_status. cURL Error: $error.";
            }
            sleep(1); // Wait for 1 second before retrying
        }
    }
    return false;
}


// Send email notification
function send_email($subject, $body, $to_email, $email_host, $email_port, $email_user, $email_pass) {
    $headers = "From: " . $email_user . "\r\n" .
               "MIME-Version: 1.0" . "\r\n" .
               "Content-type:text/html;charset=UTF-8" . "\r\n";

    $message = "<html><body>";
    $message .= "<p>" . $body . "</p>";
    $message .= "</body></html>";

    $mail_sent = mail($to_email, $subject, $message, $headers);
    if (!$mail_sent) {
        log_message('Email sending failed.');
    }
    return $mail_sent;
}

// Main function to update itemlist and send notification
function update_itemlist() {
    global $dropbox_url, $local_path, $to_email, $email_host, $email_port, $email_user, $email_pass;

    // Try downloading from Dropbox
    $result = download_file($dropbox_url, $local_path);
    if ($result === true) {
        $subject = 'Spareparts database Update Success';
        $body = 'The spareparts.xlsx database file has been successfully downloaded and updated from Dropbox.';
        log_message('File production.xlsx download successful from Dropbox.');
    } else {
        $subject = 'Spareparts.xlsx Update Failed';
        $body = 'The spareparts.xlsx file update failed from Dropbox. Error: ' . $result;
        log_message('File Spareparts.xlsx download failed from Dropbox. Error: ' . $result);
    }

    if (send_email($subject, $body, $to_email, $email_host, $email_port, $email_user, $email_pass)) {
        log_message('Email sent successfully.');
    } else {
        log_message('Email sending failed.');
    }
}

// Run the update
update_itemlist();

?>
