<?php
header('Content-Type: application/json');
require_once __DIR__ . '/auth.php';

$pdo = getDbConnection();
$myId = requireLogin();

$TWILIO_SID = 'PASTE_YOUR_TWILIO_ACCOUNT_SID_HERE';
$TWILIO_AUTH_TOKEN = 'PASTE_YOUR_TWILIO_AUTH_TOKEN_HERE';
$TWILIO_FROM_NUMBER = 'PASTE_YOUR_TWILIO_PHONE_NUMBER_HERE'; // e.g. +15551234567

if ($TWILIO_SID === 'PASTE_YOUR_TWILIO_ACCOUNT_SID_HERE') {
    http_response_code(200);
    echo json_encode(['error' => 'Phone verification is not set up yet — Twilio credentials need to be added to send-phone-otp.php on the server.']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
$phone = preg_replace('/[^0-9+]/', '', $input['phone'] ?? '');

// Require a US/Canada-style number: +1 followed by 10 digits (or bare 10 digits, we'll prefix it)
if (preg_match('/^\+?1?(\d{10})$/', $phone, $m)) {
    $phone = '+1' . $m[1];
} else {
    http_response_code(400);
    echo json_encode(['error' => 'Please enter a valid US or Canada phone number.']);
    exit;
}

$otp = str_pad((string) random_int(0, 999999), 6, '0', STR_PAD_LEFT);
$otpHash = password_hash($otp, PASSWORD_DEFAULT);
$expires = date('Y-m-d H:i:s', time() + 600); // 10 minutes

$stmt = $pdo->prepare("UPDATE users SET phone = :phone, phone_otp_hash = :hash, phone_otp_expires = :expires WHERE id = :id");
$stmt->execute([':phone' => $phone, ':hash' => $otpHash, ':expires' => $expires, ':id' => $myId]);

// Send via Twilio's REST API
$ch = curl_init("https://api.twilio.com/2010-04-01/Accounts/{$TWILIO_SID}/Messages.json");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
    'To' => $phone,
    'From' => $TWILIO_FROM_NUMBER,
    'Body' => "Your Itefaaq verification code is {$otp}. It expires in 10 minutes.",
]));
curl_setopt($ch, CURLOPT_USERPWD, "{$TWILIO_SID}:{$TWILIO_AUTH_TOKEN}");
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode >= 200 && $httpCode < 300) {
    echo json_encode(['success' => true, 'message' => 'Code sent.']);
} else {
    http_response_code(502);
    echo json_encode(['error' => 'Could not send SMS. Check Twilio credentials and phone number format.', 'detail' => $response]);
}
