<?php
// Show PHP errors during local development so blank pages are debuggable.
// === INITIALIZATION ===
error_reporting(E_ALL);
ini_set('display_errors', 1);

// PHPMailer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Twilio
use Twilio\Rest\Client;

// === SESSION AND INCLUDES ===
session_start();
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../db/db.php';
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

$phpmailerFiles = [
    __DIR__ . '/PHPMailer-master/src/Exception.php',
    __DIR__ . '/PHPMailer-master/src/PHPMailer.php',
    __DIR__ . '/PHPMailer-master/src/SMTP.php',
];
$phpmailerReady = true;
foreach ($phpmailerFiles as $file) {
    if (!file_exists($file)) {
        $phpmailerReady = false;
        break;
    }
}
if ($phpmailerReady) {
    require_once $phpmailerFiles[0];
    require_once $phpmailerFiles[1];
    require_once $phpmailerFiles[2];
}

$twilioAutoload = __DIR__ . '/vendor/autoload.php';
$twilioReady = file_exists($twilioAutoload);
if ($twilioReady) {
    require_once $twilioAutoload;
}

$message = '';
$inputError = false;
$providerMode = isset($_GET['provider']);
$providerLinks = [
    'Apple'      => 'https://appleid.apple.com/auth/authorize',
    'Google'     => 'https://accounts.google.com/',
    'Yahoo'      => 'https://login.yahoo.com/',
    'Facebook'   => 'https://www.facebook.com/login.php',
    'LinkedIn'   => 'https://www.linkedin.com/login',
    'X'          => 'https://twitter.com/i/flow/login',
    'Microsoft'  => 'https://login.live.com/',
    'Slack'      => 'https://slack.com/signin',
    'Arattai'    => 'https://www.arattai.in/',
    'GitHub'     => 'https://github.com/login',
    'Zoho'       => 'https://accounts.zoho.com/signin'
];

$slides = [1, 2];
$slide = (int)($_GET['slide'] ?? 1);
if (!in_array($slide, $slides, true)) {
    $slide = 1;
}
$nextSlide = $slide === 1 ? 2 : 1;
$auto = false;
$refreshUrl = '../signin/signin.php?slide=' . $nextSlide;
if ($providerMode) {
    $refreshUrl .= '&provider=1';
}
$refreshUrl .= '&auto=1&t=' . time();
$dotBase = '../signin/signin.php?auto=1';
$dotBaseProvider = '../signin/signin.php?provider=1&auto=1';

// === REQUEST HANDLING ===
if(isset($_POST['next'])) {
    $user = trim($_POST['user'] ?? '');
    if ($user !== '') {
        $_SESSION['user'] = $user;
    }

    if ($user === '') {
        $message = "Please enter your email address or mobile number.";
        $inputError = true;
    } else {
        $isEmail = filter_var($user, FILTER_VALIDATE_EMAIL);
        $normalizedPhone = null;

        if ($isEmail) {
            $lookupEmail = $user;
            $lookupPhone = '';
        } else {
            $digits = preg_replace('/\D+/', '', $user);
            if ($digits !== '' && strlen($digits) >= 10) {
                $normalizedPhone = substr($digits, -10);
            } else {
                $message = "Please enter a valid email address or 10-digit mobile number.";
                $inputError = true;
            }
            $lookupEmail = '';
            $lookupPhone = $normalizedPhone ?? '';
        }

        if (!$inputError) {
// === DATABASE LOOKUP ===
            $stmt = $conn->prepare("SELECT id, company_name, email, phone, org_id FROM signup WHERE email = ? OR phone = ? LIMIT 1");
            if ($stmt === false) {
                $message = "Sign-in is unavailable because the signup table is missing or not ready in the database.";
                $inputError = true;
            } else {
                $stmt->bind_param("ss", $lookupEmail, $lookupPhone);
                $stmt->execute();
                $stmt->store_result();
                if ($stmt->num_rows === 0) {
                    $message = "Account not found. Please sign up for a new account.";
                    $inputError = true;
                } else {
                    $stmt->bind_result($signupId, $foundCompany, $foundEmail, $foundPhone, $foundOrgId);
                    $stmt->fetch();
                    if (empty($foundOrgId) && !empty($signupId)) {
                        $generatedOrgId = payroll_generate_org_code((int) $signupId);
                        $orgUpdate = $conn->prepare("UPDATE signup SET org_id = ? WHERE id = ?");
                        if ($orgUpdate !== false) {
                            $orgUpdate->bind_param("si", $generatedOrgId, $signupId);
                            $orgUpdate->execute();
                            $orgUpdate->close();
                        }
                    }
                    $_SESSION['user'] = $isEmail ? $user : $normalizedPhone;
                    $_SESSION['user_company'] = $foundCompany;
                }
                $stmt->close();
            }
        }

        if ($inputError) {
            // Stop processing if user is invalid or not found
        } else {
    // Generate 6-digit OTP
// === OTP GENERATION ===
$otp = rand(100000, 999999);
    $_SESSION['otp'] = $otp;
    $_SESSION['otp_last_resend'] = time();

    // Check if input is email
    if($isEmail) {
        if ($phpmailerReady) {
            // Send Email OTP
            $mail = new PHPMailer(true);
            try {
                $mail->isSMTP();
                $mail->Host       = 'smtp.gmail.com';
                $mail->SMTPAuth   = true;
                $mail->Username   = 'your_email@gmail.com';
                $mail->Password   = 'your_app_password'; // Gmail App password
                $mail->SMTPSecure = 'tls';
                $mail->Port       = 587;

                $mail->setFrom('your_email@gmail.com', 'My Website');
                $mail->addAddress($user);

                $mail->isHTML(true);
                $mail->Subject = 'Your OTP Code';
                $mail->Body    = "Your OTP code is <b>$otp</b>";

                $mail->send();
                header("Location: ../otp/otp.php");
                exit();

            } catch (Exception $e) {
                $message = "Email could not be sent. Error: {$mail->ErrorInfo}";
                $inputError = true;
            }
        } else {
            // Demo fallback: skip email send but proceed to OTP entry
            $_SESSION['otp_hint'] = $otp;
            $_SESSION['otp_last_resend'] = time();
            header("Location: ../otp/otp.php?demo=1");
            exit();
        }

    } else {
        if ($twilioReady) {
            // Assume mobile number with country code
            $sid    = 'YOUR_TWILIO_SID';
            $token  = 'YOUR_TWILIO_AUTH_TOKEN';
            $twilio = new Client($sid, $token);

            try {
                $twilio->messages->create(
                    $user, // phone number with country code, e.g. +11234567890
                    [
                        'from' => '+YOUR_TWILIO_NUMBER',
                        'body' => "Your OTP code is $otp"
                    ]
                );
                header("Location: ../otp/otp.php");
                exit();

            } catch (Exception $e) {
                $message = "SMS could not be sent. Error: ".$e->getMessage();
                $inputError = true;
            }
        } else {
            // Demo fallback for SMS
            $_SESSION['otp_hint'] = $otp;
            $_SESSION['otp_last_resend'] = time();
            header("Location: ../otp/otp.php?demo=1");
            exit();
        }
    }
        } // end valid and found
    } // end non-empty
}
// === HTML OUTPUT ===
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sign In - Payroll</title>
<?php if ($auto): ?>
<meta http-equiv="refresh" content="5;url=<?php echo htmlspecialchars($refreshUrl); ?>">
<?php endif; ?>
<link rel="stylesheet" href="../signin.css">
<link rel="stylesheet" href="../assets/font-manrope.css"><link rel="stylesheet" href="../assets/fontawesome/css/all.min.css">
</head>
<body>

<main class="auth-shell">
    <div class="auth-card <?php echo $providerMode ? 'provider-mode' : ''; ?>" id="authCard">
        <!-- Default state -->
        <div class="default-view" aria-hidden="<?php echo $providerMode ? 'true' : 'false'; ?>">
            <section class="signin-pane">
                <div class="top-row">
                    <img src="../images/zoho-logo.svg" alt="Zoho" class="zoho-logo">
                    <a class="smart-btn" href="#" aria-label="Smart sign-in">
                        <i class="fa-solid fa-qrcode"></i>
                        <span>Try smart sign-in</span>
                    </a>
                </div>

                <h1>Sign in</h1>
                <p class="subtitle">to access Zoho Payroll</p>

                <?php if (!empty($message)): ?>
                    <div class="error-box">
                        <p><?php echo $message; ?></p>
                    </div>
                <?php endif; ?>

                <form action="" method="POST" novalidate class="signin-form">
                    <label for="user" class="sr-only">Email address or mobile number</label>
                    <input type="text" id="user" name="user" placeholder="Email address or mobile number" required class="<?php echo $inputError ? 'input-error' : ''; ?>" value="<?php echo htmlspecialchars($_SESSION['user'] ?? ''); ?>">
                    <?php if (!empty($message)): ?>
                        <div class="error-inline"><?php echo htmlspecialchars($message); ?> <a href="../signup/signup.php">sign up for a new account.</a></div>
                    <?php endif; ?>
                    <button type="submit" name="next" class="primary-btn">Next</button>
                </form>

                <div class="social-signin">
                    <p>Sign in using</p>
                <div class="social-icons">
                    <a class="icon-btn apple" aria-label="Apple" href="<?php echo $providerLinks['Apple']; ?>" target="_blank" rel="noopener">
                        <svg class="apple-svg" viewBox="0 0 20 20" aria-hidden="true">
                            <path d="M13.836 1.442a4.1 4.1 0 0 1-3.047 1.484 4.06 4.06 0 0 1 1.12-2.87A4.2 4.2 0 0 1 13.836 1.44zM17.58 11.02c-.06-1.87 1.568-2.785 1.64-2.83-.895-1.31-2.284-1.49-2.784-1.51-1.19-.12-2.324.69-2.93.69-.61 0-1.54-.68-2.53-.66-1.29.02-2.48.75-3.14 1.9-1.34 2.32-.34 5.73.96 7.6.64.91 1.4 1.95 2.4 1.91.96-.04 1.32-.62 2.48-.62 1.15 0 1.48.62 2.49.6 1.03-.02 1.69-.93 2.32-1.84.73-1.06 1.03-2.09 1.05-2.15-.02-.01-1.99-.76-2.03-2.99z"></path>
                        </svg>
                    </a>
                    <a class="icon-btn google" href="<?php echo $providerLinks['Google']; ?>" target="_blank" rel="noopener"><img src="../images/google-icon.svg" alt="Google"></a>
                    <a class="icon-btn yahoo" href="<?php echo $providerLinks['Yahoo']; ?>" target="_blank" rel="noopener"><i class="fa-brands fa-yahoo"></i></a>
                    <a class="icon-btn facebook" href="<?php echo $providerLinks['Facebook']; ?>" target="_blank" rel="noopener"><i class="fa-brands fa-facebook-f"></i></a>
                    <a class="icon-btn linkedin" href="<?php echo $providerLinks['LinkedIn']; ?>" target="_blank" rel="noopener"><i class="fa-brands fa-linkedin-in"></i></a>
                    <a class="icon-btn x" href="<?php echo $providerLinks['X']; ?>" target="_blank" rel="noopener"><i class="fa-brands fa-x-twitter"></i></a>
                    <a class="icon-btn microsoft" href="<?php echo $providerLinks['Microsoft']; ?>" target="_blank" rel="noopener"><img src="../images/microsoft-icon.svg" alt="Microsoft"></a>
                    <a class="icon-btn more" aria-expanded="false" href="?provider=1" id="moreBtn"><i class="fa-solid fa-ellipsis"></i></a>
                </div>
            </div>

                <p class="signup-hint">Don't have a Zoho account? <a href="../signup/signup.php">Sign up now</a></p>
            </section>

            <section class="promo-pane">
                <div class="banner1_img banner-rotator" aria-hidden="true">
                    <div class="banner-slide slide-1"></div>
                    <div class="banner-slide slide-2"></div>
                </div>
                <h3>MFA for all accounts</h3>
                <p>Secure online accounts with OneAuth 2FA. Back up OTP secrets and never lose access to your accounts.</p>
                <button type="button" class="secondary-btn" id="learnMoreDefault">Learn more</button>
                <div class="dot-indicator">
                    <span class="dot active"></span>
                    <span class="dot"></span>
                </div>
            </section>
        </div>

        <!-- Providers state -->
        <div class="provider-view" aria-hidden="<?php echo $providerMode ? 'false' : 'true'; ?>">
            <section class="signin-pane providers-only">
                <div class="top-row">
                    <img src="../images/zoho-logo.svg" alt="Zoho" class="zoho-logo">
                    <a class="smart-btn" href="#" aria-label="Smart sign-in">
                        <i class="fa-solid fa-qrcode"></i>
                        <span>Try smart sign-in</span>
                    </a>
                </div>

                <h1>Sign in</h1>
                <p class="subtitle">to access Zoho Payroll</p>

                <div class="provider-grid">
                    <a class="provider apple" href="<?php echo $providerLinks['Apple']; ?>" target="_blank" rel="noopener">
                        <svg class="apple-svg" viewBox="0 0 20 20" aria-hidden="true">
                            <path d="M13.836 1.442a4.1 4.1 0 0 1-3.047 1.484 4.06 4.06 0 0 1 1.12-2.87A4.2 4.2 0 0 1 13.836 1.44zM17.58 11.02c-.06-1.87 1.568-2.785 1.64-2.83-.895-1.31-2.284-1.49-2.784-1.51-1.19-.12-2.324.69-2.93.69-.61 0-1.54-.68-2.53-.66-1.29.02-2.48.75-3.14 1.9-1.34 2.32-.34 5.73.96 7.6.64.91 1.4 1.95 2.4 1.91.96-.04 1.32-.62 2.48-.62 1.15 0 1.48.62 2.49.6 1.03-.02 1.69-.93 2.32-1.84.73-1.06 1.03-2.09 1.05-2.15-.02-.01-1.99-.76-2.03-2.99z"></path>
                        </svg>
                        Sign in with Apple</a>
                    <a class="provider google" href="<?php echo $providerLinks['Google']; ?>" target="_blank" rel="noopener"><i class="fa-brands fa-google"></i>Sign in with Google</a>
                    <a class="provider yahoo" href="<?php echo $providerLinks['Yahoo']; ?>" target="_blank" rel="noopener"><i class="fa-brands fa-yahoo"></i>Sign in with Yahoo</a>
                    <a class="provider facebook" href="<?php echo $providerLinks['Facebook']; ?>" target="_blank" rel="noopener"><i class="fa-brands fa-facebook-f"></i>Sign in with Facebook</a>
                    <a class="provider linkedin" href="<?php echo $providerLinks['LinkedIn']; ?>" target="_blank" rel="noopener"><i class="fa-brands fa-linkedin-in"></i>Sign in with LinkedIn</a>
                    <a class="provider x" href="<?php echo $providerLinks['X']; ?>" target="_blank" rel="noopener"><i class="fa-brands fa-x-twitter"></i>Sign in with X</a>
                    <a class="provider microsoft" href="<?php echo $providerLinks['Microsoft']; ?>" target="_blank" rel="noopener"><img src="../images/microsoft-icon.svg" alt="Microsoft">Sign in with Microsoft</a>
                    <a class="provider slack" href="<?php echo $providerLinks['Slack']; ?>" target="_blank" rel="noopener"><i class="fa-brands fa-slack"></i>Sign in with Slack</a>
                    <a class="provider arattai" href="<?php echo $providerLinks['Arattai']; ?>" target="_blank" rel="noopener"><i class="fa-solid fa-message"></i>Sign in with Arattai</a>
                    <a class="provider github" href="<?php echo $providerLinks['GitHub']; ?>" target="_blank" rel="noopener"><i class="fa-brands fa-github"></i>Sign in with Github</a>
                </div>

                <a class="zoho-wide" id="backDefault" href="<?php echo $providerLinks['Zoho']; ?>" target="_blank" rel="noopener">Sign in with Zoho <i class="fa-solid fa-angle-right"></i></a>
            </section>

            <section class="promo-pane promo-provider">
                <div class="banner1_img banner-rotator" aria-hidden="true">
                    <div class="banner-slide slide-1"></div>
                    <div class="banner-slide slide-2"></div>
                </div>
                <h3>Passwordless sign-in</h3>
                <p>Move away from risky passwords and experience one-tap access to Zoho. Download and install OneAuth.</p>
                <button type="button" class="secondary-btn" id="learnMoreProvider">Learn more</button>
                <div class="dot-indicator">
                    <span class="dot active"></span>
                    <span class="dot"></span>
                </div>
            </section>
        </div>
    </div>

    <footer class="page-footer">&copy; 2026, Zoho Corporation Pvt. Ltd. All Rights Reserved.</footer>
</main>

</body>
</html>















