<?php
require('../config.php');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
header('Content-Type: application/json');

// ✅ Check DB connection
if (!$db) {
    echo json_encode(['status' => 'error', 'message' => 'Database connection failed']);
    exit;
}
// ✅ Get clientId from session
if (!isset($_SESSION['client_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Client ID not found in session']);
    exit;
}

$clientId = mysqli_real_escape_string($db, $_SESSION['client_id']);

if (isset($_GET['isFetchData'])) {
    $sql = "
        SELECT * FROM account_details
        INNER JOIN account_company_logo 
        ON account_details.client_id = account_company_logo.client_id
        WHERE account_details.client_id = '$clientId';
    ";
    $data = mysqli_query($db, $sql); 

    if (!$data) {
        echo json_encode(['status' => 'error', 'message' => mysqli_error($db)]);
        exit;
    }

    $rows = [];
    while ($row = mysqli_fetch_assoc($data)) {
        // Replace the actual URL with the fake URL format
        $logoFileName = !empty($row['company_logo']) ? basename($row['company_logo']) : 'dummy_image.webp';

        $companyLogoFakeUrl = "https://app.watify.io/data/$clientId/data/$logoFileName";
        $row['company_logo'] = $companyLogoFakeUrl;  // Set the fake URL
        $rows[] = $row;
    }

    echo json_encode(['status' => "success", 'data' => $rows]);
    exit;
}


if(isset($_POST['account-detail-insert'])){
    $customerTimeZone   = mysqli_real_escape_string($db, $_POST['customer-timezone']) ?? '';
    $language           = mysqli_real_escape_string($db, $_POST['language']) ?? '';
    $supportBtnEnabled  = mysqli_real_escape_string($db, $_POST['support-btn-enabled']) ?? '';
    $contentDirection   = mysqli_real_escape_string($db, $_POST['content-direction']) ?? '';
    $twoFactorAuth      = (isset($_POST['two-factor-auth']) && $_POST['two-factor-auth'] === 'true') ? 1 : 0;
    
    
    if($_POST['is-company-logo-file'] == 1){
        //check image size is not more than 2mb and image extension must be .webp
        if (isset($_FILES['company-logo'])) {
            $file = $_FILES['company-logo'];
            $fileName = $file['name'];
            $fileSize = $file['size'];
            $fileTmp = $file['tmp_name'];
            $fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
        
            if ($fileSize > 2 * 1024 * 1024) {
                echo json_encode(['status' => 'error', 'message' => 'File is too large.']);
                exit;
            } else if ($fileExtension != 'webp') {
                echo json_encode(['status' => 'error', 'message' => 'File extension must be webp.']);
                exit;
            } else {
                // Handle image
                $uploadDir = '../client_media/company_logo';
                $uniqueFileName = uniqid() . '-' . basename($fileName);
                $uploadPath = $uploadDir . '/' . $uniqueFileName;
        
                if (move_uploaded_file($fileTmp, $uploadPath)) {
                    $companyLogo = 'https://app.watify.io/client_media/company_logo/' . $uniqueFileName;
                } else {
                    echo json_encode(['status' => 'error', 'message' => 'Failed to save uploaded image']);
                    exit;
                }
            }
        } 
        else {
            echo json_encode(['status' => 'error', 'message' => 'No image files were received from the request.']);
            exit;
        }
    }
    
    $required_fields = [$customerTimeZone, $language, $supportBtnEnabled, $contentDirection, $twoFactorAuth];
    $field_names = ['Customer TimeZone', 'Language', 'Support Button Enabled', 'Content Direction', 'Two Factor Auth'];
    
    foreach ($required_fields as $index => $field) {
        if (!isset($field) || $field === '') {
            echo json_encode(['status' => 'error', 'message' => 'Missing field: ' . $field_names[$index]]);
            exit;
        }
    }
    
    // account_details
    $sql = "INSERT INTO account_details (
        client_id, customer_timezone, language, Support_button_enabled, content_direction, two_factor_authentication
    ) VALUES (
        '$clientId', '$customerTimeZone', '$language', '$supportBtnEnabled', '$contentDirection', '$twoFactorAuth'
    )
    ON DUPLICATE KEY UPDATE
        customer_timezone = VALUES(customer_timezone),
        language = VALUES(language),
        Support_button_enabled = VALUES(Support_button_enabled),
        content_direction = VALUES(content_direction),
        two_factor_authentication = VALUES(two_factor_authentication);";

    if (!mysqli_query($db, $sql)) {
        echo json_encode(['status' => 'error', 'message' => mysqli_error($db)]);
        exit;
    }

    // account_company_logo
    if($_POST['is-company-logo-file'] == 1){
        $sql = "INSERT INTO account_company_logo (
            client_id, company_logo
        ) VALUES (
            '$clientId', '$companyLogo'
        )
        ON DUPLICATE KEY UPDATE
            company_logo = VALUES(company_logo);";
    }
    
    if (!mysqli_query($db, $sql)) {
        echo json_encode(['status' => 'error', 'message' => mysqli_error($db)]);
        exit;
    }

    
    if (!mysqli_query($db, $sql)) {
        echo json_encode(['status' => 'error', 'message' => mysqli_error($db)]);
        exit;
    }
    
    echo json_encode(['status' => 'success', 'message' => "Details Saved Successfully!"]);
    exit;
}